Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 623
kiran Avatar asked Feb 08 '11 10:02

kiran


People also ask

What happens when you divide two integers in Java?

When dividing two integers, Java uses integer division. In integer division, the result is also an integer. The result is truncated (the fractional part is thrown away) and not rounded to the closest integer.

Why does division return float?

The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the 'floor' function applied to the result. The result of flooring is safe to convert to an integer.


2 Answers

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);
like image 91
unwind Avatar answered Oct 17 '22 07:10

unwind


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;
like image 23
Peter Lawrey Avatar answered Oct 17 '22 07:10

Peter Lawrey