Consider the following java code:
String toParse = "1.7976931348623157E308"; //max value of a double in java
double parsed = Double.parseDouble(toParse);
System.out.println(parsed);
For the mentioned value of 1.7976931348623157E308
everything makes sense and one gets the correct output.
Now, if one tries to parse 1.7976931348623158E308
(last digit before E
incremented) you still get the maximum value printed into the console!
Only after trying to parse 1.7976931348623159E308
(again the last digit got incremented) and greater one gets Infinity
.
Same behaviour for the corresponding negative values.
Why is ... 8E308
parsed to ... 7E308
and not Infinity
?
The SE 7 version of the parseDouble documentation refers to the valueOf documentation which says:
This is consistent with the statement that the rounding to type double is by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic.
You have to imagine the conversion being done by first calculating the nearest floating point number ignoring the exponent limitation, and then checking whether the exponent fits. Double.MAX_VALUE is the closest number under that rule to some numbers that are strictly greater than it.
To confirm this is normal rounding behavior, consider the following program:
It outputs:
Adding something even slightly less than half a ulp to Double.MAX_VALUE does not change it. Adding half a ulp overflows to infinity.