Can anybody figure out how the following statement evaluates to 7?
echo (int)( (0.1+0.7)*10 );
I was trying the operator precedence in PHP. So, if there is anybody who can help, it will be highly appreciated.
Can anybody figure out how the following statement evaluates to 7?
echo (int)( (0.1+0.7)*10 );
I was trying the operator precedence in PHP. So, if there is anybody who can help, it will be highly appreciated.
If you remove the (int)
part, and run the follwing code instead:
echo number_format(((0.1+0.7)*10), 20);
The output will be 7.99999999999999911182
. This value parsed to an integer will result to 7, as parsing a value to an integer will always floor the value.
Reading the following article should give you an idea of what's going on here.
In short, double values are always a binary value, and through that a 'product of 2^n', whichever will be the nearest to the decimal you said it should be. And with 2^n you dont have any chance to reach exactly 0.1.