PHP integer rounding problems

后端 未结 5 1194
-上瘾入骨i
-上瘾入骨i 2021-01-13 08:31

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

5条回答
  •  清歌不尽
    2021-01-13 08:59

    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:

    • http://en.wikipedia.org/wiki/Binary_numeral_system

    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.

提交回复
热议问题