PHP 中向浮点数添加整数会将浮点数四舍五入到小数点后 1 位
例如,我有这行代码:
echo 10359023529 + 0.2137582935;
为什么会返回:
10359023529.2
而不是:
10359023529.2137582935
For example, I have this line of code:
echo 10359023529 + 0.2137582935;
Why does this return:
10359023529.2
instead of:
10359023529.2137582935
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用:
bcadd()
Use:
bcadd()
这就是浮点值的限制。浮点值存储为系数和指数。对于小数字,您将获得很高的精度;对于大数字,您将获得低精度。这里有比您想要的更多详细信息: http://en.wikipedia.org/wiki/IEEE_754- 2008
底线:高值将非常不精确。尝试使用较小的值范围。
以下是有关 PHP 的浮点精度的更多信息:http://php。 net/manual/en/language.types.float.php
如果你确实需要高精度和高数字,请查看 BC 数学 ( http://www.php.net/manual/en/ref.bc.php ) 和 GMP ( http://www.php.net/manual/en/ref.gmp.php )。
That's the limitation of a floating point value. A floating point value is stored as a coefficient and exponent. You'll have lots of precision with small numbers, and low precision with high numbers. Here is more detail than you would want: http://en.wikipedia.org/wiki/IEEE_754-2008
Bottom line: High values will be very imprecise. Try to use a small value range.
Here's more about the floating point precision specifically in regards to PHP: http://php.net/manual/en/language.types.float.php
If you really need high precision and high numbers, look at BC math ( http://www.php.net/manual/en/ref.bc.php ) and GMP ( http://www.php.net/manual/en/ref.gmp.php ).
php.ini 中有一个晦涩的选项,它定义了打印浮点数时要显示多少位有效数字。在我的例子中,它看起来如下
当然,这仅涉及格式化,而不是浮点数本质上不精确的基本事实。根据 IEEE 754,double 的精度为 15.95 位十进制数字。
There is an obscure option in
php.ini
that defines how many significant digits to show when printing floating point numbers. In my case it looks as followsOf course this deals only with formatting, not the fundamental fact that floating-point numbers are inherently imprecise. According to IEEE 754 the precision of double is 15.95 decimal digits.