Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ceil function strange behavior ?

Tags:

php

ceil

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

like image 368
lorandd Avatar asked Nov 25 '11 14:11

lorandd


2 Answers

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.

like image 189
Kerrek SB Avatar answered Nov 03 '22 09:11

Kerrek SB


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.

like image 3
Marc B Avatar answered Nov 03 '22 08:11

Marc B