if I try to print
echo ((0.1 + 0.7) * 10);
output (http://codepad.org/m3mNNO77)
8
but if I try to print
echo (int)((0.1 + 0.7) * 10);
output (http://codepad.org/8OTCnlVG)
7
why two different results ?
if I try to print
echo ((0.1 + 0.7) * 10);
output (http://codepad.org/m3mNNO77)
8
but if I try to print
echo (int)((0.1 + 0.7) * 10);
output (http://codepad.org/8OTCnlVG)
7
why two different results ?
If you perform the echo
without the (int)
cast, it resulits in:
echo ((0.1 + 0.7) * 10);
8
So what happens is that the floating point actually represents it as 7.99999....
When you perform an (int)
cast, the default behavior is to take the integral part, so that's 7
. Although it is extremely close to 8
, it is not the behavior of a cast to round off.
The errors are due to the fact that floating point numbers are represented with a binary radix. Representing 0.8
correctly is thus impossible. Floating points round off the answers, and hope it doesn't bother that much. When you represent the floating point like 0.8
, the result is 0.80000...
Proof of concept using the PHP interactive shell (php -a
):
$ php -a
Interactive mode enabled
php > echo number_format(((0.1 + 0.7) * 10),20)."\n";
7.99999999999999911182
php > echo number_format(0.8,20);
0.80000000000000004441
As you may be aware, floating point math is not exact due to restrictions in their representation.
(0.1 + 0.7) * 10
works out to something like 7.99999999999...
.
When echo
'd out, the number is converted to a string using rounding, which uses the php.ini precision
setting (15 by default, I believe) to limit the number of decimal numbers. It happens that this rounding gives exactly 8
.
However, (int)
casts the float to an integer instead, and this is done with truncation. It doesn't matter how close to the next integer up you are, it will always round down. This is why you get 7
here.