Java: trying to get percentage of integers, how to round?

I have two integer values: x and total. I am trying to find the percentage of x overall as an integer. This is how I do it right now:

percent = (int) ((x * 100) / total);

Percentage must be an integer. When I do this, it always rounds the decimal point down. Is there an easy way to calculate the percentage as an integer so that it rounds up if the decimal digit is .5 or higher?

+3


source to share


7 replies


Use Math.round(x * 100.0/total)

. But note that this returns long, so a simple conversion to int

.



I put 100.0 to force it to use floating point arithmetic before rounding.

+13


source


(int)Math.round(100.0 / total * x);

      



must work.

+3


source


Just use Math.round(100.0 / total * x);

+2


source


Why not use Math.round((x*100)/total);

+1


source


Use the standard math library in Java.

percentage = Math.round(*your expression here*);

      

+1


source


You can add 0.5 for positive values ​​(round to infinity)

percentage = (int)(x * 100.0 / total + 0.5);

      

It's faster than using Math.round, but maybe not as clear.

BTW: 100.0 / total * x

May not give the same result x * 100.0 / total

as the order of evaluation can change the result for floating point.

+1


source


The simplest method is

Question: How to round the decimal value (ex: int n = 4.57)

Answer: Math.round (n);

Exit: 5.

0


source







All Articles