php float 数学运算错误?
这里的摘要:
$a = 213480.7-190.46;
exit($a-213290.24);
# 2.9103830456734E-11
结果输出假设为 0。但它输出了
操作结果的故事:
$b is : 213480.7
-190.46
$b is : 213290.24
现在余额看起来是正确的。但是当使用比较运算符时..结果很奇怪 这是 var_dump 和比较结果
var_dump($b);
# float 213290.24
if ($b==213290.24) {
exit('same');
} elseif ($b>213290.24) {
exit('larger '.($b-213290.24));
} else {
exit('smaller '.($b-213290.24));
}
#larger 2.9103830456734E-11
谁能告诉我如何解决它?
the summary here:
$a = 213480.7-190.46;
exit($a-213290.24);
# 2.9103830456734E-11
the result output suppose to be 0. but it output
the story of the operation result :
$b is : 213480.7
-190.46
$b is : 213290.24
now the balance looks correct. but when use comparison operator.. the result is weird
here is the var_dump and compare result
var_dump($b);
# float 213290.24
if ($b==213290.24) {
exit('same');
} elseif ($b>213290.24) {
exit('larger '.($b-213290.24));
} else {
exit('smaller '.($b-213290.24));
}
#larger 2.9103830456734E-11
can anyone tell me how to solve it??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅此处:http://php.net/manual/en/language.types。浮动.php
处理浮点比较的常用方法是添加允许的 epsilon,即浮点值的小差异,因此小容差内的任何内容都被认为是等效的。
See here: http://php.net/manual/en/language.types.float.php
The common method of dealing with float comparisons is to add an allowable epsilon, or small difference in floating point values, so anything within a small tolerance is considered equivalent.
对浮点数值执行的计算始终会因机器表示而产生固有错误。因此,不应使用相等运算符
==
来比较浮点值。典型的方法是确定最小允许误差,并检查要比较的值之间的差异是否小于所需的误差。
Computations performed on floating point numeric values always have inherent error resulting from their machine representation. For this reason, you should not use the equality operator
==
to compare floating point values.The typical approach is to decide on a minimum allowable error, and check if the difference between the values you want to compare is less than the desired error.
这不是php的问题,它与二进制浮点数的性质有关。
你不能用浮点数准确地表示所有有理数。例如,您可能尝试比较 0.1 + 0.2 == 0.3,它会失败,因为 0.3 没有准确表示。
This is not problem of php, it's connected with the nature of binary float.
You can't represent all rational number accurately with float. For example, you might try to compare 0.1 + 0.2 == 0.3, it will be failse, because 0.3 is not represented accurately.