why is the Double.parseDouble making 9999999999999999 to 10000000000000000?

double, java

Solution

`double` only has 15/16 digits of accuracy and when you give it a number it can't represent (which is most of the time, even 0.1 is not accurate) it takes the closest representable number.

If you want to represent `9999999999999999` exactly, you need to use BigDecimal.

BigDecimal bd = new BigDecimal("9999999999999999");
System.out.println(new DecimalFormat("#.##").format(bd));

prints

9999999999999999

Very few real world problems need this accuracy because you can't measure anything this accurately anyway. i.e. to an error of 1 part per quintillion.

You can find the largest representable integer with

// search all the powers of 2 until  (x + 1) - x != 1
for (long l = 1; l > 0; l <<= 1) {
    double d0 = l;
    double d1 = l + 1;
    if (d1 - d0 != 1) {
        System.out.println("Cannot represent " + (l + 1) + " was " + d1);
        break;
    }
}

prints

Cannot represent 9007199254740993 was 9.007199254740992E15

The largest representable integer is 9007199254740992 as it needs one less bit (as its even)

Problem

why is the Double.parseDouble making `9999999999999999` to `10000000000000000` ? For Example : ``` Double d =Double.parseDouble("9999999999999999"); String b= new DecimalFormat("#.##").format(d); System.out.println(b); ``` IS Printing ``` 10000000000000000 ``` instead it has to show `9999999999999999` or `9999999999999999.00` Any sort of help is greatly appreciated.

Original source

Related problems