0

Can anybody figure out how the following statement evaluates to 7?

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

I was trying the operator precedence in PHP. So, if there is anybody who can help, it will be highly appreciated.

1 Answers1

3

If you remove the (int) part, and run the follwing code instead:

echo number_format(((0.1+0.7)*10), 20);

The output will be 7.99999999999999911182. This value parsed to an integer will result to 7, as parsing a value to an integer will always floor the value. Reading the following article should give you an idea of what's going on here.

In short, double values are always a binary value, and through that a 'product of 2^n', whichever will be the nearest to the decimal you said it should be. And with 2^n you dont have any chance to reach exactly 0.1.

Michael Kunst
  • 2,978
  • 25
  • 40
  • Pony story puts a smile on my face and is complete true. And some extra proof printf("%b", (0.1+0.7)*10); // 111 binary 7 decimal – Raymond Nijland Aug 14 '13 at 17:47