Timo Nentwig said:
Can somebody explain why the following code does output 2009 (at least on an
Athlon XP machine, Window/Linux, jdk1.3 and 1.5)?
class Bug
{
public static void main( final String[] args )
{
final double d = 2.010d;
System.out.println( (long)( d * 1000d) );
}
}
Because the value 2.010 can't be stored excactly in the finite
number of bits that represent a double datatype.
For that particular value, something like 2.00999999999...99998 is stored
It uses the IEEE standard 754 for binary floating-point:
The IEEE double precision floating point standard representation requires a
64 bit word, which may be represented as numbered from 0 to 63, left to
right. The first bit is the sign bit, S, the next eleven bits are the
exponent bits, 'E', and the final 52 bits are the fraction 'F':
S EEEEEEEEEEE FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
0 1 11 12 63
The value V represented by the word may be determined as follows:
If E=2047 and F is nonzero, then V=NaN ("Not a number")
If E=2047 and F is zero and S is 1, then V=-Infinity
If E=2047 and F is zero and S is 0, then V=Infinity
If 0<E<2047 then V=(-1)**S * 2 ** (E-1023) * (1.F) where "1.F" is intended
to represent the binary number created by prefixing F with an implicit
leading 1 and a binary point.
If E=0 and F is nonzero, then V=(-1)**S * 2 ** (-1022) * (0.F) These are
"unnormalized" values.
If E=0 and F is zero and S is 1, then V=-0
If E=0 and F is zero and S is 0, then V=0