echo (int) ( (0.1+0.7) * 10 );
Why does the above output 7? I understand how PHP rounds towards 0, but isn\'t (0.1+0.7) * 10 evaluated as
I don't have php installed, but in python:
$ python
>>> 0.1+0.7
0.79999999999999993
>>>
Not all numbers in base 10 can be represented precisely in base 2 system. Check Wikipedia article:
section Fractions in Binary. In particular, this line:
Fraction Decimal Binary Fractional Approx.
1/10 0.1 0.000110011... 1/16+1/32+1/256...
1/10 cannot be represented in a finite way in base 2. Thus, 0.1 + 0.7 cannot be precisely calculated in base 2.
Never assume floating-point calculations are precise, it will bite you sooner or later.