解决js加减乘除运算小数丢失精度的问题

// 解决浮动运算问题,避免小数点后产生多位数和计算精度损失。

class Precision {
  // 乘法
  times (num1, num2, ...others) {
    if (others.length > 0) {
      return this.times(this.times(num1, num2), ...others)
    }
    const num1Changed = this.float2Fixed(num1)
    const num2Changed = this.float2Fixed(num2)
    // 把两个数的小数位数相加
    const baseNum = this.digitLength(num1) + this.digitLength(num2)
    const leftValue = num1Changed * num2Changed
    this.checkBoundary(leftValue)
    return leftValue / Math.pow(10, baseNum)
  }
  // 精确加法
  plus (num1, num2, ...others) {
    if (others.length > 0) {
      return this.plus(this.plus(num1, num2), ...others)
    }
    const baseNum = Math.pow(10, Math.max(this.digitLength(num1), this.digitLength(num2)))
    return (this.times(num1, baseNum) + this.times(num2, baseNum)) / baseNum
  }
  // 精确减法
  minus (num1, num2, ...others) {
    if (others.length > 0) {
      return this.minus(this.minus(num1, num2), ...others)
    }
    const baseNum = Math.pow(10, Math.max(this.digitLength(num1), this.digitLength(num2)))
    return (this.times(num1, baseNum) - this.times(num2, baseNum)) / baseNum
  }
  // 精确除法
  divide (num1, num2, ...others) {
    if (others.length > 0) {
      return this.divide(this.divide(num1, num2), ...others)
    }
    const num1Change = this.float2Fixed(num1)
    const num2Change = this.float2Fixed(num2)
    return this.times(num1Change / num2Change, Math.pow(10, this.digitLength(num2) - this.digitLength(num1)))
  }
  // 四舍五入,且保留小数
  round (num, ratio) {
    const base = Math.pow(10, ratio)
    return this.divide(Math.round(this.times(num, base)), base)
  }
  // 把小数转成整数,支持科学计数法。如果是小数则放大成整数
  float2Fixed (num) {
    if (~num.toString().indexOf('e')) {
      return Number(num.toString().replace('.', ''))
    }
    const dlen = this.digitLength(num)
    return dlen > 0 ? num * Math.pow(10, dlen) : num
  }
  // 获取当前数小数位的长度(处理科学计数法,本质上处理e-n的情况)
  digitLength (num) {
    const eSplit = num.toString().split(/[eE]/)
    const len = (eSplit[0].split('.')[1]|| '').length - (+ eSplit[1] || 0)
    return len > 0 ? len : 0
  }
  //  检测数字是否越界,如果越界给出提示
  checkBoundary(num) {
    if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
      console.log(`${num} is beyond boundary when transfer to integer, the results may not be accurate`)
    }
  }
}
let precision = new Precision()
console.log(precision.times(0.1, 0.2, 0.3))
console.log(precision.plus(0.1, 0.2))
console.log(precision.minus(0.1, 0.2))
console.log(precision.divide(0.1, 0.2))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue中,可以使用第三方库Decimal.js解决小数的四则运算导致精度丢失问题。Decimal.js是一个用于高精度数值计算的JavaScript库。 首先,需要在Vue项目中通过npm安装Decimal.js库。可以使用以下命令进行安装: ``` npm install decimal.js --save ``` 安装完成后,在需要使用的组件中引入Decimal.js库: ``` import Decimal from 'decimal.js'; ``` 然后,就可以使用Decimal.js库中提供的方法进行小数的四则运算了。 下面是一个示例代码,演示如何使用Decimal.js进行乘除运算并避免精度丢失问题: ```vue <template> <div> <p>运算结果:{{ addResult }}</p> <p>运算结果:{{ subResult }}</p> <p>乘法运算结果:{{ mulResult }}</p> <p>除法运算结果:{{ divResult }}</p> </div> </template> <script> import Decimal from 'decimal.js'; export default { data() { return { addResult: 0, subResult: 0, mulResult: 0, divResult: 0, }; }, mounted() { // 运算 this.addResult = new Decimal(0.1).plus(0.2).toNumber(); // 运算 this.subResult = new Decimal(0.3).minus(0.1).toNumber(); // 乘法运算 this.mulResult = new Decimal(0.1).times(0.2).toNumber(); // 除法运算 this.divResult = new Decimal(0.3).dividedBy(0.1).toNumber(); }, }; </script> ``` 在上述示例代码中,首先通过`import`语句引入了Decimal.js库。然后,通过`new Decimal()`创建Decimal对象,并使用Decimal对象的方法进行乘除运算。最后,使用`toNumber()`方法将结果转换为普通的JavaScript数字类型,并将结果渲染到模板中。 通过使用Decimal.js库,可以避免小数四则运算导致的精度丢失问题,保证计算结果的准确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值