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

后端 未结 6 1637
刺人心
刺人心 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:49

    As has been explained, this is due to very small floating point precision.

    This can be resolve via using a Math.round(), command, as follows:

    long j=Math.round(i*100);
    

    This will allow the program to compensate for the very small errors which are inherit using floating point calculations, by not using a floor operation, as the default (long) does.

提交回复
热议问题