作用
- 解决 JS 小数计算精度问题(
0.1 + 0.2 ≠ 0.3) - 开启
BigNumber高精度计算模式 - 可设置保留指定位数有效数字,计算更安全准确
基本用法
import { create, all } from 'mathjs'
const config = {
number: 'BigNumber', // 开启高精度计算
precision: 20 // 保留20位有效数字
}
const math = create(all, config)
// 加
math.add(0.1, 0.2) // 0.1 + 0.2
// 减
math.subtract(0.3, 0.1) // 0.3 - 0.1
// 乘
math.multiply(0.1, 0.2) // 0.1 * 0.2
// 除
math.divide(1, 3) // 1 / 3
// 计算结果是 BigNumber 对象,需要转成正常数字/字符串
const res = math.add(0.1, 0.2)
res.toNumber() // 转数字 0.3
res.toString() // 转字符串 "0.3"
math.round(res, 2) // 保留2位小数
使用场景
- 金额、价格、税费计算
- 涉及小数的加减乘除
- 科学计算、高精度数据