duuliy

你不知道的js计算

2023-3-26

big.js

工作中会遇到很多计算,有一些事超过了js计算精度怎么处理呢?
1.小数后面+0,用整数计算
2.bigInt
3.https://github.com/duuliy/jsoo/blob/master/%E7%AE%97%E6%B3%95/test1.html 大正整数相加/相乘
4.第三方,eg: big.js http://mikemcl.github.io/big.js/#toF

但是依然会出现一些问题:

图片

这个时候要么继续找其他第三方,要么自己解决:

// 空值,类型, number转string 等过程省略
const getToFixed = (str, dec) => {
  const SYMBOL = '-'
  const isSymbol = str[0] === SYMBOL
  const _str = isSymbol ? str.slice(1) : str

  if (/^\d+\.0*\d+$/i.test(_str)) {
    const newStr = _str.replace(/^(\d+\.0*)(\d+)$/i, (com, v, c) => v + c.slice(0, dec))
    return isSymbol ? SYMBOL + newStr : newStr
  }

}