0

I can't understand why first print is 0.9999999999999 and second is 2.0.

public static void main(String[] args) {

       double value = 0.9999999999999999;

       System.out.println(value);

       value = 1.9999999999999999;

       System.out.println(value);
    }
Nevada
  • 277
  • 1
  • 7
  • 13
  • Remember that computers use binary and limited memory. That number can't be stored well in binary with its limited memory, so it gets truncated to something that it *can* store. – 4castle Jun 06 '16 at 17:35
  • @4castle That number *can* be stored in binary. It cannot be stored with accuracy in a *floating-point* number, but there are other binary representations that can store it correctly. – Andreas Jun 06 '16 at 17:36
  • For the first value you specify 16 significant digits, for the second you specify 17. – FredK Jun 06 '16 at 17:38
  • @Andreas Only an object like `BigDecimal`, but there aren't any primitive types in Java that can. – 4castle Jun 06 '16 at 17:40
  • @4castle I know that, but you didn't say *primitive type*, you just said *binary*, so I was trying to point out that your wording was wrong, since `BigDecimal` stores values in *binary* too, and it can store values like that just fine. – Andreas Jun 06 '16 at 17:47
  • @4castle thank you, now I understand. – Nevada Jun 06 '16 at 18:16

0 Answers0