Can somebody explain this ?
echo ceil( 20.7 * 100 ); // returns 2070
echo ceil( 2070 ); // returns 2070
all OK and logical, but
echo ceil( 40.7 * 100 ); // returns 4071
echo ceil( 4070 ); // returns 4070
not OK and not logical...
Why is this difference ?
Thanks
The wonderful world of floating point numbers:
printf("%.18f\n", 40.7*100);
//prints 4070.000000000000454747
printf("%.18f\n", 20.7*100);
//prints 2070.000000000000000000
In short: floating point numbers cannot represent all rational numbers exactly. In particular, neither 407/10 nor 207/10 can be represented exactly, and so the result of integer conversion always has an uncertainty of one unit.
The only rational numbers which can be represented exactly as binary floating point numbers are of the form "small odd integer times power of two", or in other words, those which have a small binary expansion.
Floating point errors. 40.7 cannot be represented exactly in a float. It'll be something like 40.700000001 or whatever. When you * 100
and ceil it, it rounds up to 4071.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With