0

While testing this simple piece of code in eclipse, I found that the numbers after the decimal are not accurate always. Why is that?

int kj = 1;
float we = 1.1f;
double dd = we + kj ; // prints 2.0999999046325684!!

int kj = 1, kl = 1;
float we = 11.1f;
double dd = we + kj + kl; //prints 13.100000381469727
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
eminemence
  • 721
  • 1
  • 6
  • 21
  • 1
    A key to what you are observing that is not made clear in the purported originals is that Java conceals some floating-point rounding by not displaying the true values. By default, Java shows only enough digits to uniquely distinguish a `float` or `double` from its neighboring representable values. Thus both a float `1.1f` and a double `1.1` are displayed as “1.1” even though they have different values. When you add various values together, especially from different types, they often produce results that are not near short decimal numerals, so the default formatting needs more digits. – Eric Postpischil Jul 14 '19 at 12:34
  • So it means, it can be any value as long as it approximates to the digits specified. So a 1.1 can always be represented as 1.09734657834673468734 as it approximates to 1.1f. – eminemence Jul 14 '19 at 12:49
  • 2
    No, there are specific rules. The **only** `float` that is displayed as “1.1” by the default formatting is 1.10000002384185791015625, and the **only** `double` that is displayed as “1.1” by the default formatting is 1.100000000000000088817841970012523233890533447265625. In fact, if the former value, which is displayed as “1.1” when it is a `float`, is stored in a `double` and then formatted, is displayed as “1.100000023841858”—because, as a `double`, it is not the `double` value nearest 1.1 and hence needs more digits to distinguish it. – Eric Postpischil Jul 14 '19 at 13:07
  • I have written [several answers](https://stackoverflow.com/search?q=user%3A298225+%5Bjava%5D+uniquely) about this. – Eric Postpischil Jul 14 '19 at 13:07

0 Answers0