Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Division Float Value Issue

Tags:

php

math

decimal

When I Try get remainder, It gives invalid value. I am trying to get remained of two decimal values and I get

3.4694469519536E-18

My Values are

 $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 is 0.1 will be divide by 0.005 in 20 times. i.e. 0.1/0.005 = 20

The same function returns correct value when I use 10%1 = 0.

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

Check an Work Around: PHP Division Float Value WorkAround

like image 725
DonOfDen Avatar asked Aug 15 '26 04:08

DonOfDen


1 Answers

The % operator just works on integers, so it truncates your floats to integers and tries to do 0 % 0, which results in a division by zero.

The only thing you can use is fmod(). The issue you face here is the typical floating point imprecision (the value is "nearly" zero). I'd consider to just ignore values smaller then 10^-15. There's no real alternative to this in PHP.

What you could try is doing the real division, then, with a bit of luck traces of the imprecision disappear. (like round(0.1 / 0.005) === 0.1 / 0.005)

like image 84
bwoebi Avatar answered Aug 16 '26 18:08

bwoebi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!