开发者

Adding an integer to a float in PHP rounds the float to 1 decimal place

开发者 https://www.devze.com 2023-01-20 13:33 出处:网络
For example, I have this line of code: echo 开发者_运维问答10359023529 + 0.2137582935; Why does this return:

For example, I have this line of code:

echo 开发者_运维问答10359023529 + 0.2137582935;

Why does this return:

10359023529.2

instead of:

10359023529.2137582935


Use: bcadd()

echo bcadd(10359023529, 0.2137582935, 10);


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 ).


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 follows

; The number of significant digits displayed in floating point numbers.
; http://php.net/precision
precision = 14

Of 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号