Java: Trying to get the percentage of integers, how to round up?
33,010
Solution 1
Use Math.round(x * 100.0/total)
. But note that this returns a long, so a simple cast to int
will be required.
I put 100.0 to force it to use floating point arithmetic prior to the rounding.
Solution 2
(int)Math.round(100.0 / total * x);
should work.
Solution 3
Just use Math.round(100.0 / total * x);
Solution 4
Use the standard math library in Java.
percentage = Math.round(*your expression here*);
Solution 5
Why not use Math.round((x*100)/total);
Related videos on Youtube
Author by
Petefic
Updated on June 08, 2020Comments
-
Petefic almost 4 years
I have two integer values, x and total. I am trying to find the percentage of x in total as an integer. This is how I am doing it right now:
percentage = (int)((x*100)/total);
The percentage must be an integer. When I do this it always rounds the decimal point down. Is there a simple way to calculate the percentage as an integer so it rounds up if the decimal is .5 or higher?
-
Dharini Chandrasekaran about 12 yearsThere is an overloaded method which returns int. So a cast isn't absolutely necessary.
-
joshuahealy about 12 years@DhariniChandrasekaran I believe it returns an int if you pass in a float? The way I've written it it will pass in a double and return a long.
-
joshuahealy about 12 years@Churk actually I edited my answer because x, 100 and total were all ints so the arithmetic would've all been integers and the call to round would've been a waste of time. I changed to 100.0 to make it use floating point arithmetic and then added an explanation for it.
-
joshuahealy about 12 years@Churk perhaps you should take a look at the revisions of my answer before making silly false accusations.
-
joshuahealy about 12 yearsThis answer doesn't solve the problem as
x
andtotal
are both integers. The expression will be evaluated using integer arithmetic and will be "rounded" down before being passed into the round function. -
Stephane Delcroix almost 11 yearsIt only partially answer the question. could you elaborate to form a complete answer ?
-
Andrew Barber almost 11 yearsIt's also not correct; you may want to read the question more carefully, and check out the many existing answers which correctly answer it.