php中相近的数字相减
为什么
输出
0.0099999999999909
我在这里缺少什么?这是 php 5.2。
Why does
<?php echo 194.95-194.94; ?>
output
0.0099999999999909
What am i missing here? This is php 5.2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是你不能用浮点数精确地表示 0.01。
看看每个程序员都应该了解浮点知识,以获得关于其原因的详细解释,以及该怎么办。
The issue is that you cannot represent 0.01 exactly in floating point.
Have a look at what every programmer should know about floating point for a great explanation of why this is, and what to do about it.
虽然马克的答案是好的,但它可能仍然让你想知道为什么你会得到这样的答案。例如,尝试
PHP 愉快地打印
0.01
。在您的情况下,
194.95
和194.94
都以 IEEE 754 中可以容纳的接近二进制形式存储,并且它们的差异与基本的0.01
,可以被“正确”渲染。在在线计算器上尝试您的示例,例如 http://babbage.cs.qc .edu/IEEE-754/Decimal.html。应该很有趣。
While Mark's answer is okay, it may still leave you wondering why you got the answer you did. For example, try
PHP happily prints
0.01
.In your case
194.95
and194.94
were both stored in as-close-a-binary-form as could be accommodated in IEEE 754, and their difference was too far away from the basic0.01
that could be rendered "properly".Try out your example on an online calcuator such as http://babbage.cs.qc.edu/IEEE-754/Decimal.html. Should be interesting.