percentage of two int?

前端 未结 5 674
说谎
说谎 2020-12-12 23:59

I want to get two ints, one divided by the other to get a decimal or percentage. How can I get a percentage or decimal of these two ints? (I\'m not sure if it is right.. I\'

相关标签:
5条回答
  • 2020-12-13 00:16

    If you don't add .0f it will be treated like it is an integer, and an integer division is a lot different from a floating point division indeed :)

    float percent = (n * 100.0f) / v;
    

    If you need an integer out of this you can of course cast the float or the double again in integer.

    int percent = (int)((n * 100.0f) / v);
    

    If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.

    int percent = (n * 100) / v;
    

    If you get NaN is because wathever you do you cannot divide for zero of course... it doesn't make sense.

    0 讨论(0)
  • 2020-12-13 00:16

    One of them has to be a float going in. One possible way of ensuring that is:

    float percent = (float) n/v * 100;
    

    Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.

    The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.

    0 讨论(0)
  • 2020-12-13 00:21

    Well to make the decimal into a percent you can do this,

    float percentage = (correct * 100.0f) / questionNum;
    
    0 讨论(0)
  • 2020-12-13 00:31
    float percent = (n / (v * 1.0f)) *100
    
    0 讨论(0)
  • 2020-12-13 00:38

    Two options:

    Do the division after the multiplication:

    int n = 25;
    int v = 100;
    int percent = n * 100 / v;
    

    Convert an int to a float before dividing

    int n = 25;
    int v = 100;
    float percent = n * 100f / v;
    //Or:
    //  float percent = (float) n * 100 / v;
    //  float percent = n * 100 / (float) v;
    
    0 讨论(0)
提交回复
热议问题