1

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
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43

1 Answers1

4
$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.

Vural
  • 8,666
  • 11
  • 40
  • 57