js处理运算精度丢失问题

问题描述
99.99 / 100 -> 0.9998999999999999
2.332 + 0.215 -> 2.5469999999999997
5.52 -2 -> 3.5199999999999996
8.005*10 -> 80.05000000000001
由于计算机二进制处理以及计算机位数限制,会造成js运算中一些精度丢失

解决方案

//type 1 加法 2 乘法 3减法(number1 被减数, number2 减数) 4除法(number1被除数 number2 除数)
export function coefficient(number1: any, number2: any, type = 2) {
  const num1 = Number(number1)
  const num2 = Number(number2)
  // 判断参数是否是number
  if (isNaN(num1) || isNaN(num2)) {
    return
  }
  // 除数不能为0
  if (number2 === 0 && type === 4) {
    return
  }
  // 获取小数点后位数
  const len1 = String(num1).split('.')[1]?.length || 0
  const len2 = String(num2).split('.')[1]?.length || 0
  const len = Math.max(len1, len2)
  // 返回值
  let total = 0

  if (type === 1) {
    //加法
    total = Number(
      (coefficient(num1, Math.pow(10, len), 2)! +
        coefficient(num2, Math.pow(10, len), 2)!) /
        Math.pow(10, len)
    )
  } else if (type === 2) {
    //乘法
    // 通过字符串替换属性,替换小数点达到变成整数的效果
    const res1 = Number(num1.toString().replace('.', ''))
    const res2 = Number(num2.toString().replace('.', ''))

    total = (res1 * res2) / Math.pow(10, len1 + len2)
    return Number(total)
  } else if (type === 3) {
    total = Number(
      (coefficient(num1, Math.pow(10, len), 2)! -
        coefficient(num2, Math.pow(10, len), 2)!) /
        Math.pow(10, len)
    )
  } else if (type === 4) {
    // 通过字符串替换属性,替换小数点达到变成整数的效果
    const res1 = Number(num1.toString().replace('.', ''))
    const res2 = Number(num2.toString().replace('.', ''))

    total = Number(coefficient(res1 / res2, Math.pow(10, len2 - len1)))
  }
  return total
}

如有不足,欢迎大佬指点.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值