PHP 中的舍入
$a = ((0.1 + 0.7) * 10) == (int)((0.1 + 0.7) * 10);
PHP 返回 false。
有人能给我解释一下,为什么会发生这种情况吗? 第一个返回 8,第二个返回 7。
$a = ((0.1 + 0.7) * 10) == (int)((0.1 + 0.7) * 10);
PHP returns false.
Could anybody explain me, why that happens?
First returns 8, second 7.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
引用 PHP 浮点精度手册中的大红色警告:
Quoting the big fat red warning in the PHP Manual on Floating Point Precision:
浮点运算并不精确。您可以获得 7.999,而不是 8.0...当转换为整数时,它会被截断为 7。
结果:
Floating point arithmetic is not precise. Instead of 8.0 exactly you can get 7.999... which gets truncated to 7 when cast to an integer.
Result:
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
编辑
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
EDIT
马克的回答击中了要害,但我认为您不需要强制转换,而是需要圆形 PHP 函数:
http://php.net/manual/en/function.round.php
Mark's response hits the nail on the head, but I think instead of casting you want the round PHP function:
http://php.net/manual/en/function.round.php
来自浮点指南(点击查看详细说明):
From The Flaoting-Point Guide (click for detailed explanations):
因为对浮点数进行操作并不是 100% 准确,所以在从表达式中转换值之前可能类似于 7.9999...
Because operating on floating point numbers isn't 100% accurate, propably before casting value from expression is something like 7.9999...
您可以这样进行比较:
You can do the comparison this way: