Funny PHP #3 – Why (int) ((0.2 + 0.4) x 10) equals 5, not 6

Let’s see this example:

<?php
echo (int) ((0.2 + 0.4) * 10);
?>

It will print 5, not 6.
Have you tested? Ok. But why it happens?

Just because in expression “(0.2 + 0.4) * 10” there are 2 floating numbers 0.2 and 0.4, so PHP considers that the expression result should be floating number. As 6 is integer number, to distinguish 6 and 6.000 PHP stores second one as a 5.99999…
And when we try to print (int) ((0.2 + 0.4) * 10) expression, PHP cuts fractional part of expression and prints whole number part, aka 5.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.