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

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

    When you do this kind of long conversion it's floor. Your 17.31 could actually be 17.30999999999 and that's why it resulted in 1730 instead of 1731.

    use i = i * 100, then i.longValue() will solve the problem.

提交回复
热议问题