views:

42

answers:

3

For example, I have this line of code:

echo 10359023529 + 0.2137582935;

Why does this return:

10359023529.2

instead of:

10359023529.2137582935

+3  A: 

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

EboMike
A: 

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.

Adam Byrtek
The output precision isn't the issue; the float data type is only so precise.
meagar
In principle you are right, but in this particular case he didn't exceed the double precision.
Adam Byrtek
@Adam I believe he did, actually; otherwise his implementation has been specifically set to only display one decimal place when outputting floating point numbers, as the default is 14.
meagar
Interestingly my command line PHP displays 10359023529.214 by default (precision 14).
Adam Byrtek
@Adam Then at a guess I'd say your platform has higher precision floating point numbers than James'
meagar
I don't think so, the precision of double is exactly defined by the IEEE 754 standard as 15.95 decimal digits.
Adam Byrtek
+1  A: 

Use: bcadd()

echo bcadd(10359023529, 0.2137582935, 10);
Ruel