percentage of two int?

前端 未结 5 695
说谎
说谎 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

    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.

提交回复
热议问题