Why does the division of two integers return 0.0 in Java? [duplicate]
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Solution 1:
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
Solution 2:
If you are using int
values, using a double
may be a better choice and have less rounding error. float
can represent int
values without error up to ~16 million. double
can accurately represent all int
values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
Solution 3:
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int
which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0
value to double so you got 0.0
as result
0.0
and then you can change the result to any format as suggeted by @Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Solution 4:
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)