前端计算精度丢失问题

发布时间:2024年01月10日
// 精度丢失异常数据汇总
10.3950 * 3935.00 = 期望40904.33, 异常结果40904.32
7.3950 * 3835.00 = 期望28359.83, 异常结果28359.82
11.777 * 4215 = 期望49640.06, 异常结果49640.05
12.445 * 4005 = 期望49842.23,异常结果49842.22
3721*17.0480 = 期望63435.61,异常结果63435.60
3621*5.0060 = 期望18126.73,异常结果18126.72

vue项目中直接装插件

npm install bignumber.js
import { BigNumber } from 'bignumber.js';
// +
export function add(a, b) {
  a = BigNumber(a);
  b = BigNumber(b);
  return a.plus(b).toNumber();   //结果需要用toNumber转为普通数字
}
// -
export function minus(a, b) {
  a = BigNumber(a);
  b = BigNumber(b);
  return a.minus(b).toNumber();
}
// *
export function mut(a, b) {
  a = BigNumber(a);
  b = BigNumber(b);
  return a.multipliedBy(b).toNumber();
}
// /
export function dev(a, b) {
  a = BigNumber(a);
  b = BigNumber(b);
  return a.dividedBy(b).toNumber();
}

界面中使用:

import {
	add,
	minus,
	mut,
	dev
} from '@/utils/common.js' //公共方法

row.amountStr = (this.mut(Number(row.salePriceStr), Number(row.weightStr))).toFixed(2)

toFixed也有精度丢失问题,直接main.js中改写toFixed方法

Number.prototype.toFixed = function(d) {
  var s = this + ''
  if (!d) d = 0
  if (s.indexOf('.') === -1) s += '.'
  s += new Array(d + 1).join('0')
  if (new RegExp('^(-|\\+)?(\\d+(\\.\\d{0,' + (d + 1) + '})?)\\d*$').test(s)) {
    let s = '0' + RegExp.$2; var pm = RegExp.$1; var a = RegExp.$3.length; var b = true
    if (a === d + 2) {
      a = s.match(/\d/g)
      if (parseInt(a[a.length - 1]) > 4) {
        for (var i = a.length - 2; i >= 0; i--) {
          a[i] = parseInt(a[i]) + 1
          if (a[i] === 10) {
            a[i] = 0
            b = i !== 1
          } else break
        }
      }
      s = a.join('').replace(new RegExp('(\\d+)(\\d{' + d + '})\\d$'), '$1.$2')
    }
    if (b) s = s.substr(1)
    return (pm + s).replace(/\.$/, '')
  }
  return this + ''
}

如果vue3中遇到精度丢失问题,可以创建一个fixed.js文件

// // js
if (!Number.prototype._toFixed) {
	// eslint-disable-next-line no-extend-native
	Number.prototype._toFixed = Number.prototype.toFixed
}
// eslint-disable-next-line no-extend-native
Number.prototype.toFixed = function (d) {
	let s = this + ''
	if (!d) {
		d = 0
	}
	if (s.indexOf('.') === -1) {
		s += '.'
	}
	s += new Array(d + 1).join('0')
	if (new RegExp('^(-|\\+)?(\\d+(\\.\\d{0,' + (d + 1) + '})?)\\d*$').test(s)) {
		let s = '0' + RegExp.$2
		let pm = RegExp.$1
		let a = RegExp.$3.length
		let b = true
		if (a === d + 2) {
			a = s.match(/\d/g)
			if (parseInt(a[a.length - 1]) > 4) {
				for (let i = a.length - 2; i >= 0; i--) {
					a[i] = parseInt(a[i]) + 1
					if (a[i] === 10) {
						a[i] = 0
						b = i !== 1
					} else {
						break
					}
				}
			}
			s = a.join('').replace(new RegExp('(\\d+)(\\d{' + d + '})\\d$'), '$1.$2')
		}
		if (b) {
			s = s.substr(1)
		}
		return (pm + s).replace(/\.$/, '')
	}
	return this + ''
}

然后再main.ts文件中引入即可

import '@/utils/fixed'

方式二: 封装js方法

// 乘法
function highPrecisionMul(data1, data2) {
  let m = 0;
  const s1 = data1.toString();
  const s2 = data2.toString();
  // 获取所有参数小数位长度之和
  try {
    m += s1.split(".")[1].length;
  } catch (e) { e => e }
  try {
    m += s2.split(".")[1].length;
  } catch (e) { e => e }
  // 替换掉小数点转为数字相乘再除以10的次幂值
  return (
    (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
    Math.pow(10, m)
  );
};

// 加法

function highPrecisionAdd(data1, data2) {
  let r1, r2;
  // 获取每个参数的小数的位数
  try {
    r1 = data1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = data2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  // 计算底数为10以最大小数位数为次幂的值
  const m = Math.pow(10, Math.max(r1, r2));
  // 把所有参数转为整数后相加再除以次幂的值
  return (data1 * m + data2 * m) / m;
};


// toFixed精度问题  重写

function toSuperFixed(n, d) {
  var s = n + "";
  if (!d) d = 0;
  if (s.indexOf(".") === -1) s += ".";
  s += new Array(d + 1).join("0");
  if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) {
    let s = "0" + RegExp.$2; var pm = RegExp.$1; var a = RegExp.$3.length; var b = true;
    if (a === d + 2) {
      a = s.match(/\d/g);
      if (parseInt(a[a.length - 1]) > 4) {
        for (var i = a.length - 2; i >= 0; i--) {
          a[i] = parseInt(a[i]) + 1;
          if (a[i] === 10) {
            a[i] = 0;
            b = i !== 1;
          } else break;
        }
      }
      s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2");
    }
    if (b) s = s.substr(1);
    return (pm + s).replace(/\.$/, "");
  }
  return this + "";
}

使用:

this.toSuperFixed(this.highPrecisionMul(Number(row.priceStr), Number(row.weightStr)), 2)
文章来源:https://blog.csdn.net/CuiCui_web/article/details/135511027
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。