Search code examples
phpfloor

floor(24.24*1e4) returns wrong value


Performing some coordinates rounding, I came to some bug or something, with different numbers it works as I needed

$res = floor(24.24*1e4)/1e4;
echo $res;

returns 24.2399

Do You know what is so special with this 242400, that it's returns 242399?


Solution

  • The problem is related to floating point precision

    Even though the PHP manual says "Returns the next lowest integer value by rounding down value if necessary." if you read further down the page for "return values" in the PHP manual for floor() you'll see:

    value rounded to the next lowest integer. The return value of floor() is still of type float because the value range of float is usually bigger than that of integer.

    When we checkout float types we see a warning:

    Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.