Possible Duplicate:
Elegant workaround for JavaScript floating point number problem




对于基于1985年使用的IEEE 754标准,Javascript无法可靠地进行浮点运算的事实,我需要一种变通方法。基本上,我需要的是一种评估表达式的方式,如5 + 3 *(2 + 8/6)。我正在考虑使用字符串完成此操作,并为基本操作(+-* /%)滚动我自己的函数,但是我首先想知道您是否已经知道任何执行此操作的库。

最佳答案

这取决于数字的大小。对于较小的数字(例如,少于14个有效数字),四舍五入到可接受的精度可能会起作用。例如给你的例子:

var n = 0.5 / 5 + 1 / 5;  // 0.30000000000000004

var p = Math.pow(10, 14); // where 14 is calculated based on the first
                          // significant digit and its relationship to
                          // the decimal place

n = Math.round(n * p) / p;  // 0.3


计算10的功效并不难。如果数量众多,那么生活会更困难(请参阅现有库)。

10-05 20:29
查看更多