Zairov Muric Zairov Muric - 2 months ago 7
PHP Question

Why do these expressions always return 7?

I am really interested to know, why the following code returns always 7. I am really confused.

$a = (double) ((0.1 + 0.6) * 10); //Output: 7
$b = (int) ((0.1 + 0.6) * 10); //Output: 7
$c = (int) ((0.1 + 0.7) * 10); //Output: 7


output test:

echo ($a == $b && $a == $c); //Output: true

Answer
$a = (double) ((0.1 + 0.6) * 10); //Output: 7
$b = (int)    ((0.1 + 0.6) * 10); //Output: 7
$c = (int)    ((0.1 + 0.7) * 10); //Output: 7

theoretically (0.1 + 0.7) * 10 part should evaluate to 8 not 7.

Output of the third expression in the script evaluates to 7 because the PHP engine stores the value of the expression internally as 7.999999 instead of 7.

And when the fractional value is converted into an integer, PHP engine simply truncates the fractional part.