Double multiplied by 100 and then cast to long is giving wrong value

后端 未结 6 1630
刺人心
刺人心 2020-12-25 10:27

I have the following code:

Double i=17.31;
long j=(long) (i*100);
System.out.println(j);

O/P : 1730 //Expected:1731

6条回答
  •  遥遥无期
    2020-12-25 10:33

    The double value is represented not as 17.31, but as 17.309999999999999. That's why when you multiply it by 100 you get 1730.99999999999999999. After conversion to Long your double value is truncated towards zero. So you get 1730.

提交回复
热议问题