In floating point, all numbers are represented internally as fractions where the denominator is a power of 2.
(This is a similar way to how decimals are actually fractions with power-of-10 denominators. So 31.15
is just a way of writing the fraction 3115/100
)
In floating point, 31.15
must be represented internally as a binary number. The closest binary fraction is: 1111.1001001100110011001100110011001100110011001100110011001100...repeating
The 1100
recurs (repeats forever), and so the number will be truncated depending on whether it is stored in a double or a float. In a float it is truncated to 24 digits, and in a double to 53.
Exact: 1111.100100110011001100110011001100110011001100110011001100110011001100...forever
Float: 1111.10010011001100110011
Double: 1111.1001001100110011001100110011001100110011001100110
Therefore you can see that the double that this number converts to, is actually slightly larger than the float it converts to. So it is clear that it won't necessarily round to the same number, since it is not the same number to begin with.
(float)31.15
is not equal to(double)31.15
. Floating-point-arithmetic allmost allways yields to rounding-erros. In paticular rounding a double works different from rounding a float. – HimBromBeere Jan 17 at 12:26float
exists. – SeM Jan 17 at 12:33float
. – SeM Jan 17 at 13:29