在PHP中舍入 [英] Rounding in PHP
问题描述
PHP返回false。
解释我,为什么会发生?
首先返回8,第二个7。
通常情况下,简单的小数点如
0.1
或0.7
不能是转换成其内部的二进制对应,而不会有小的精度损失。这可能会导致令人困惑的结果:例如,floor((0.1 + 0.7)* 10)
通常会返回7
而不是所期望的8
,因为内部表示将类似于7.9
。
这是由于这样的事实,即不可能用有限的数字来表示一些十进制符号的分数。例如,小数形式的
1/3
变成0.3
。
所以不要相信浮点数结果到最后一个数字,也不要比较浮点数是否相等。如果需要更高的精确度,任意精度数学函数和 gmp 功能可用。
$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.
Quoting the big fat red warning in the PHP Manual on Floating Point Precision:
It is typical that simple decimal fractions like
0.1
or0.7
cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example,floor((0.1+0.7)*10)
will usually return7
instead of the expected8
, since the internal representation will be something like7.9
.This is due to the fact that it is impossible to express some fractions in decimal notation with a finite number of digits. For instance,
1/3
in decimal form becomes0.3
.So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.
这篇关于在PHP中舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!