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?
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.
(int)Math.round(100.0 / total * x);
must work.
Just use Math.round(100.0 / total * x);
Why not use Math.round((x*100)/total);
Use the standard math library in Java.
percentage = Math.round(*your expression here*);
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.
The simplest method is
Question: How to round the decimal value (ex: int n = 4.57)
Answer: Math.round (n);
Exit: 5.