PHP Unit Floating Value Issue

When I try to get the remainder, it gives an invalid value. I am trying to get the remaining two decimal values ​​and I am getting

3.4694469519536E-18

My values

 $x=0.1; $y=0.005;

      

I tried the following:

echo $ed = fmod(0.1,0.005);  OutPut:3.4694469519536E-18
echo $ed = ((floatval(0.1)) % (floatval(0.005)));

      

But getting

Warning: Division by zero

      

But Reality 0.1 will divide by 0.005 20 times. those.0.1/0.005 = 20

This same function returns the correct value when I use 10%1 = 0

.

How can I get the exact remainder. (I don't face the same problem in JQuery :))

Check Job: Float Value PHP Division Work Schedule

+3


source to share


1 answer


The operator %

only works with integers, so it truncates your floats with integers and tries to execute 0 % 0

, which results in division by zero.

The only thing you can use is fmod()

. The problem you are having here is a typical floating point imprecision (the value "almost" is zero). I would like to just ignore values ​​less than 10 ^ -15. There is no real alternative to this in PHP.



What you could try is to do a real division, and then, with a slight offset, the inaccuracy disappeared. (for example round(0.1 / 0.005) === 0.1 / 0.005

)

+3


source







All Articles