1

I was writing test cases in which i saw following behaviour. If some one can describe this in layman terms. Adding tag IEEE 754.

70D * 1.1 = 77.0 50D * 1.1 = 55.00000000000001 ?

xingbin
  • 27,410
  • 9
  • 53
  • 103
mrcodename
  • 11
  • 2
  • 2
    ObLink: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html But really, this "issue" with floating point is something you should be able to look up on your own; it’s a multiple-dupe question on SO and all over the web. – Dave Newton Jun 01 '18 at 15:19
  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Rudy Velthuis Jun 01 '18 at 17:17

1 Answers1

2

Double value has precision problem, you can use java.math.BigDecimal to get accurate result:

System.out.println(new BigDecimal("50").multiply(new BigDecimal("1.1"))); // 55.00
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • @RudyVelthuis I tried. On `java version "10.0.1"`, it works fine. – xingbin Jun 01 '18 at 17:29
  • This one does, because for `valueOf()`, Java uses a roundtrip format. For other values, this is still bound to fail. The inaccuracy introduced by using FP can not always be "corrected" by `valueOf()`. – Rudy Velthuis Jun 01 '18 at 17:38