Below I attempt to assign to value the maximum Long value, then add to it the minimum positive Double value possible.
I then try to detect that the value is greater than the maximum Long value.
Double value = new Long(Long.MAX_VALUE).doubleValue();
value += Double.MIN_VALUE;
if (value < -(new Long(Long.MAX_VALUE).doubleValue()) || value > new Long(Long.MAX_VALUE).doubleValue()) {
// Expecting code here to execute, but it doesn't.
}
Studying the values involved shows that value has the final value of
9.223372036854776E18
= 9223372036854776000
while Long.MAX_VALUE has the value
9223372036854775807
Comparing these shows that value is greater as expected:
9223372036854776000 (value)
9223372036854775807 (Long.MAX_VALUE)
Could someone please explain why the if statement fails to detect this?
Sincere thanks.
Long.MAX_VALUEcan’t be represented exactly as a double. The closest available double value is9223372036854775808.Adding
Double.MIN_VALUEto that number (10^-1074) does not change anything because the closest double value to9223372036854775808 + 10^-1074still is9223372036854775808.Using @PeterLawrey’s code, you can see that the next available double is
9223372036854777856(which is equal toLong.MAX_VALUE + 2048).Note: your double is actually equal to
9223372036854775808, which gets printed as9.223372036854776E18. You can see it with the following code: