Gender (24.24 * 1e4) returns an invalid value

Performing some rounding of coordinates, I got into some kind of error or something like that, with different numbers that I need

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

returns 24.2399

Do you know what is so special with this 242400 that it returns 242399?

+4
source share
2 answers

The problem is with floating point precision

Although the PHP manual says: "Returns the next lower integer value, rounding the value if necessary." if you read further the "return values" page in the PHP manual for floor () , you will see:

the value is rounded to the next minor integer. The return value of floor() is still of type float , since the range of float values ​​is usually larger than an integer.

When we check the float , 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 the maximum relative error due to rounding in the order of 1.11e-16. Non-elementary arithmetic operations can produce large errors, and, of course, the propagation of errors should be considered when several operations are exacerbated.

+3
source

Your error is caused by the float value, sometimes it happens.

Have you tried this?

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

Or you can use a round with an optional parameter to round in a specific decimal format.

In your example:

 round($res, 4) 
+1
source

All Articles