Home > other >  My double variable has got 2 values? Java [duplicate]
My double variable has got 2 values? Java [duplicate]

Time:09-16

I'll keep it short. I've got this basic java code:

int listLength = sc.nextInt();
double[] list = new double[listLength];

for(int i = 0; i < list.length; i  ){
   list[i] = sc.nextDouble();
}

When I input 1 12345678901234567 Now if I execute this line: System.out.println(list[0] == 12345678901234568.0 && list[0] == 12345678901234567.0);

The console will print: true

If I just print list[0], it prints 12345678901234568

I ask the console to print if a double value is 2 different numbers and it says it's true. How is this possible?

CodePudding user response:

The Java double-precision float can store between 15-16 digits before the decimal point in the number because that's what the IEEE 754 floating-point standard allows for the maximum integer part. Your number is 17 digits. Try the same test after rounding/truncating a few digits off and it should work as expected.

CodePudding user response:

Not all numbers can be represented exactly with a double, because there are infinitely many numbers, and only finitely many double values. If you try to store a number in a double, and there's no double value that represents it exactly, you'll get the nearest (or nearest equal) value that can be represented.

In your particular case, 12345678901234567 can't be represented exactly with a double, so whenever you write 12345678901234567.0, the double that's actually stored is the nearest (or nearest equal) available one, which is the one representing 12345678901234568.

  •  Tags:  
  • java
  • Related