Question

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?

Was it helpful?

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.

OTHER TIPS

Your error is due to float value, sometimes it happens.

Have you tried this?

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

Or you can use round with an optional parameter to round up at a specific decimal.

For your example :

round($res, 4)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top