1

I found somewhere in book

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

output is : 7

echo ((0.1 + 0.7) * 10);

output : 8

why both out are different ? I think answer should be 8

Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78

3 Answers3

6

When you write

echo ((0.1 + 0.7) * 10);

the result of this simple arithmetic expression is stored internally as 7.999999 instead of 8.

Now when the value is converted to int,

 echo (int) ((0.1 + 0.7) * 10); // 7.999999 when typecasted to int becomes 7

PHP simply truncates away the fractional part, resulting in a rather significant error (12.5%, to be exact).

Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
2

It's because float point at this scenario does not fit to memory and is truncated when converting to integer.

Read about that in PHP manual about float

Warning

Floating point precision

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Community
  • 1
  • 1
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

Please check http://php.net/manual/en/language.types.integer.php and find this

Warning : Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.
<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

See also the warning about float precision. 
Brijal Savaliya
  • 1,101
  • 9
  • 19