This question already has answers here:
Is floating point math broken?
                            
                                (33个答案)
                            
                    
                4年前关闭。
        

    

我刚刚在JavaScript上尝试过非常简单的计算,如下所示:
8.87 + 7.1,但输出是如此不可预测:15.969999999999999
谁能解释为什么?以及如何预防呢?
我正在使用Chrome执行计算

最佳答案

二进制数不能存储100%准确的浮点值。因此,会出现像您这样的错误。看一下以下参考:

Floating point inaccuracy examples

What causes floating point rounding errors?

What Every Computer Scientist Should Know About Floating-Point Arithmetic

10-07 23:20