JS浮点计算精度丢失

333 阅读1分钟

最近有项目需要用到前端进行实时计算,但是考虑到一个大问题,js用于浮点数计算会导致精度丢失。

方案一

使用放大N倍后,然后进行取整进行计算。

方案二

使用bignumber.js进行解决。

安装并导入项目

npm install bignumber.js --save

使用方法

加法
0.1 + 0.2                       // 0.30000000000000004
x = new BigNumber(0.1)
y = x.plus(0.2)                 // '0.3'
BigNumber(0.7).plus(x).plus(y)  // '1'
x.plus('0.1', 8)                // '0.225'
console.log(x.toString());
减法
0.3 - 0.1                       // 0.19999999999999998
x = new BigNumber(0.3)
x.minus(0.1)                    // '0.2'
x.minus(0.6, 20)                // '0'
乘法
0.6 * 3                         // 1.7999999999999998
x = new BigNumber(0.6)
y = x.multipliedBy(3)           // '1.8'
BigNumber('7e+500').times(y)    // '1.26e+501'
x.multipliedBy('-a', 16)        // '-6

更多api请自行探索。mikemcl.github.io/bignumber.j…

github: github.com/MikeMcl/big…