vue使用mathjs,解决前端计算精度不足问题
在前端开发过程中,你会发现0.1 * 0.2 != 0.2 如下图
他居然等于0.020000000000000004…
为什么会这样大家可以百度,涉及到10进制和2进制的转换问题,我们暂不讨论,我们先来解决这个问题。
现在有现成的库给我们调用 math.js
首先先安装依赖
npm install mathjs --save
然后再需要计算的页面调用
import * as math from 'mathjs'
加法
// 原本
console.log(0.1 + 0.2) // 0.30000000000000004
// 用math.js之后
const addNumber = math.format(
math.add(
math.bignumber(0.1),math.bignumber(0.2)
)
)
console.log(addNumber) // 0.3
减法
// 原本
console.log(1 - 0.9) // 0.09999999999999998
// 用math.js之后
const subtractNumber = math.format(
math.subtract(
math.bignumber(1), math.bignumber(0.9)
)
)
consol(subtractNumber) // 0.1
乘法</