PHP unexpected result of float to int type cast

This is because numbers that have a finite representation in base 10 may or may not have an exact representation in the floating point representation PHP uses.

See

>php -r "echo var_dump(sprintf('%.40F', 39.3 * 100.0));"
string(45) "3929.9999999999995452526491135358810424804688"

Since int always rounds the number down, a small error in the representation makes the cast round it one number down that you would otherwise expect.

Consider using round instead.

Leave a Comment