0

I want to know the reason why i am getting so many decimal points while doing this sum of double numbers

System.out.println(Double.parseDouble(".56"));
double dvalue=1.12+Double.parseDouble(".56");
System.out.println(dvalue);

output is as follows 0.56 and 1.6800000000000002 why second summation is adding those decimals it should simply 1.68

M A
  • 71,713
  • 13
  • 134
  • 174
Ravo
  • 41
  • 2
  • 7
  • Take a look at Floating Point arithmetic on [Wikipedia](http://en.wikipedia.org/wiki/Floating_point). – Sascha Wolf Jan 15 '15 at 10:14
  • Related: http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – Sascha Wolf Jan 15 '15 at 10:15
  • OK - this will be closed as a many time duplicate, I'm sure - but for the OP here is, in my opinion, the best link to explain this http://floating-point-gui.de/ – J Richard Snape Jan 15 '15 at 10:18

1 Answers1

4

It's because the addition of the doubles 1.12 and 0.56 does not yield an exact representation of 1.68 (it doesn't precisely result in 1.68). You can see the difference with this code:

System.out.println(1.12+0.56);   // 1.6800000000000002
System.out.println(1.68);        // 1.68
M A
  • 71,713
  • 13
  • 134
  • 174
  • It is true that 1.68 cannot be represented exactly in binary floating-point format, but this has nothing to do with what happens in the question. **Exactly one `double` floating-point number is printed by `System.out.println` as "1.68".** The question is why `1.12+Double.parseDouble(".56")` does not compute this `double`. The answer to that is that 1.12 is not represented exactly, that 0.56 is not represented exactly, and that `+` is not mathematical addition. – Pascal Cuoq Jan 15 '15 at 10:53
  • To illustrate how “1.68 cannot be represented exactly” is simply the wrong answer, one can imagine a different question in which the mathematical result of a sequence of operations would have been 4, and the operations interpreted as floating-point operations produce the result `0x1.0000000000001p2`. Would you say that the reason for this superficially surprising result is that 4 cannot be represented exactly as a `double`? – Pascal Cuoq Jan 15 '15 at 10:58
  • @PascalCuoq Your comments make perfect sense. The answer is now updated. Thanks for the correction! – M A Jan 15 '15 at 11:14
  • 1
    As it happens, in this particular case, the addition gets the same answer as real number addition for the same inputs. The inputs are 1.12000000000000010658141036401502788066864013671875 and 0.560000000000000053290705182007513940334320068359375, sum 1.680000000000000159872115546022541821002960205078125. – Patricia Shanahan Jan 15 '15 at 13:08