why is the Double.parseDouble making 9999999999999

2019-02-16 08:43发布

问题:

This question already has an answer here:

  • How to resolve a Java Rounding Double issue [duplicate] 13 answers

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.

回答1:

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)



回答2:

The number 9999999999999999 is just above the precision limit of double-precision floating-point. In other words, the 53-bit mantissa is not able to hold 9999999999999999.

So the result is that it is rounded to the nearest double-precision value - which is 10000000000000000.

 9999999999999999 = 0x2386f26fc0ffff  // 54 significant bits needed
10000000000000000 = 0x2386f26fc10000  // 38 significant bits needed


回答3:

9999999999999999 requires 54 bits of mantissa in order to be represented exactly, and double only has 52. The number is therefore rounded to the nearest number that can be represented using a 52-bit mantissa. This number happens to be 10000000000000000.

The reason 10000000000000000 requires fewer bits is that its binary representation ends in a lot of zeroes, and those zeroes can get represented by increasing the (binary) exponent.

For detailed explanation of a similar problem, see Why is (long)9223372036854665200d giving me 9223372036854665216?



标签: java double