doujiao9574 2015-01-05 14:22
浏览 351
已采纳

PHP奇怪的浮点不精确

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 ?

  • 写回答

2条回答 默认 最新

  • dqf42223 2015-01-05 14:24
    关注

    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)."
    ";
    7.99999999999999911182
    php > echo number_format(0.8,20);
    0.80000000000000004441
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?