phprounding-error

PHP - Converting a String float to an Integer - Wrong value


Why does this code provide 853 instead of 854?

(int) ((float) ( "8.54") * 100);

How do I convert (string) "8.54" into (integer) 854?


Solution

  • First of all, read Is floating point math broken?

    8.54 happens to be one of those numbers which can be written precisely in decimal, but not in binary, so (float)"8.54" will actually create a number very very close to, but slightly under, 8.54.

    Multiplying that by 100 will create a number very very close to, but slightly under, 854. And casting to int will find the next smallest integer (e.g. 853.9 becomes 853, not 854).

    I can think of two solutions: