Why does the division of two integers return 0.0 in Java?

kiran picture kiran · Feb 8, 2011 · Viewed 73.2k times · Source
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?

Answer

unwind picture unwind · Feb 8, 2011

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);