PHP部门浮动价值问题 [英] PHP Division Float Value Issue
问题描述
当我尝试获得余数时,它给出了无效的值.我试图保留两个十进制值,然后得到
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
3.4694469519536E-18
我的价值观是
$x=0.1; $y=0.005;
我尝试了以下操作:
echo $ed = fmod(0.1,0.005); OutPut:3.4694469519536E-18
echo $ed = ((floatval(0.1)) % (floatval(0.005)));
但是得到
Warning: Division by zero
但现实"为0.1会在 20 次中除以0.005.即0.1/0.005 = 20
But Reality is 0.1 will be divide by 0.005 in 20 times. i.e. 0.1/0.005 = 20
当我使用10%1 = 0
时,同一函数返回正确的值.
The same function returns correct value when I use 10%1 = 0
.
如何获得确切的余数. (我在JQuery中没有遇到相同的问题:))
How can I get the exact remainder. ( I don't face the same issue in JQuery :) )
检查变通方法: PHP部门浮点值替代方案
推荐答案
%
运算符仅适用于整数,因此它将浮点数截断为整数并尝试执行0 % 0
,结果除以零.
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.
您唯一可以使用的是fmod()
.您在这里面临的问题是典型的浮点不精确度(该值接近"零).我会考虑忽略小于10 ^ -15的值.在PHP中没有真正的替代方法.
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.
您可以尝试做的是真正的划分,然后,一些不精确的运气消失了. (如round(0.1 / 0.005) === 0.1 / 0.005
)
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
)
这篇关于PHP部门浮动价值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!