PHP - 浮点数精度 [英] PHP - Floating Number Precision
问题描述
$ a ='35';
$ b ='-34.99';
echo($ a + $ b);
结果为0.009999999999998
接着就,随即?为什么PHP不会返回预期的0.01?
>解决方案
因为浮点运算!=实数运算。由于不精确性的差异,对于一些花车 a
和 b
,( a + b)-b!= a
。这适用于使用浮动的任何语言。
由于浮点数是二进制有限精度的数字,有限数量的可表示的数字,精确度问题和这样的惊喜。这是另一个有趣的阅读:计算机科学家应该知道什么关于浮点运算
一>。回到你的问题,基本上没有办法准确地表示二进制的34.99或0.01(就像十进制, 1/3 = 0.3333 ...),所以使用近似值。为了解决这个问题,你可以:
-
使用
round($ result,2)
将结果舍入到小数点后两位。
-
使用整数。如果是货币,例如美元,那么存储35.00美元为3500和34.99美元,然后将结果除以100。
Use
round($result, 2)
on the result to round it to 2 decimal places.Use integers. If that's currency, say US dollars, then store $35.00 as 3500 and $34.99 as 3499, then divide the result by 100.
可惜的是,PHP没有十进制数据类型,如其他 languages 。
$a = '35';
$b = '-34.99';
echo ($a + $b);
Results in 0.009999999999998
What is up with that? I wondered why my program kept reporting odd results.
Why doesn't PHP return the expected 0.01?
Because floating point arithmetic != real number arithmetic. An illustration of the difference due to imprecision is, for some floats a
and b
, (a+b)-b != a
. This applies to any language using floats.
Since floating point are binary numbers with finite precision, there's a finite amount of representable numbers, which leads accuracy problems and surprises like this. Here's another interesting read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Back to your problem, basically there is no way to accurately represent 34.99 or 0.01 in binary (just like in decimal, 1/3 = 0.3333...), so approximations are used instead. To get around the problem, you can:
It's a pity that PHP doesn't have a decimal datatype like other languages do.
这篇关于PHP - 浮点数精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!