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

亡梦爱人 提交于 2019-12-16 19:58:28

问题


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?


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



回答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;



回答3:


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




回答4:


(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.




回答5:


String.format("%2.02f", (float)totalOptCount/totalRespCount);



回答6:


to format a double and print out as a percentage, you can use use

System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));


来源:https://stackoverflow.com/questions/4931892/why-does-the-division-of-two-integers-return-0-0-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!