1

if I try to print

echo ((0.1 + 0.7) * 10);

output (http://codepad.org/m3mNNO77)

8

but if I try to print

echo (int)((0.1 + 0.7) * 10);

output (http://codepad.org/8OTCnlVG)

7

why two different results ?

Simone Nigro
  • 4,717
  • 2
  • 37
  • 72
  • 2
    http://php.net/manual/en/language.types.float.php – Pevara Jan 05 '15 at 14:25
  • 1
    Re-opening this question because, while we have seen floating point errors countless times, this is a particularly interesting edge case that is completely unrelated to the "duplicate". – Niet the Dark Absol Jan 05 '15 at 14:27

2 Answers2

3

If you perform the echo without the (int) cast, it resulits in:

echo ((0.1 + 0.7) * 10);
8

So what happens is that the floating point actually represents it as 7.99999....

When you perform an (int) cast, the default behavior is to take the integral part, so that's 7. Although it is extremely close to 8, it is not the behavior of a cast to round off.

The errors are due to the fact that floating point numbers are represented with a binary radix. Representing 0.8 correctly is thus impossible. Floating points round off the answers, and hope it doesn't bother that much. When you represent the floating point like 0.8, the result is 0.80000...

Proof of concept using the PHP interactive shell (php -a):

$ php -a
Interactive mode enabled

php > echo number_format(((0.1 + 0.7) * 10),20)."\n";
7.99999999999999911182
php > echo number_format(0.8,20);
0.80000000000000004441
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
3

As you may be aware, floating point math is not exact due to restrictions in their representation.

(0.1 + 0.7) * 10 works out to something like 7.99999999999....

When echo'd out, the number is converted to a string using rounding, which uses the php.ini precision setting (15 by default, I believe) to limit the number of decimal numbers. It happens that this rounding gives exactly 8.

However, (int) casts the float to an integer instead, and this is done with truncation. It doesn't matter how close to the next integer up you are, it will always round down. This is why you get 7 here.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592