PHP Division Float Value Issue

社会主义新天地 提交于 2019-12-23 19:28:16

问题


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


回答1:


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)



来源:https://stackoverflow.com/questions/26038538/php-division-float-value-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!