Home  >  Article  >  Backend Development  >  PHP中浮点数精密度的警告

PHP中浮点数精密度的警告

WBOY
WBOYOriginal
2016-06-13 13:06:42903browse

PHP中浮点数精度的警告

这个是PHP document中给出来的提示:


简单的十进制分数如同 0.10.7 不能在不丢失一点点精度的情况下转换为内部二进制的格式。

floor(( 0.1 + 0.7 ) * 10)? ?返回 7 而不是8

(int)(( 0.1 + 0.7 ) * 10) ?返回7而不是8.

?

对这种现象的解释是“因为该结果内部的表示其实是类似 7.9”。

?

所以得到的结论是:

所以永远不要相信浮点数结果精确到了最后一位,也永远不要比较两个浮点数是否相等。

决不要将未知的分数强制转换为Int。

?

(int)round( 0.1 + 0.7 ) * 10) 这样似乎就安全了。

在有大量乘除或者是中间值为float类型时,为了数值精度还是使用BC math函数了。

?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn