js,vue前端小数加减计算精度问题处理(化整计算小数据)

//化整计算
//处理小数,返回小数点后有效位数
let decimalLength = (n) => {
return n.toString().substring(n.toString().lastIndexOf('.')+1).length;
};
//加法运算
let addOperation = (a,b)=>{
let al = decimalLength(a),bl = decimalLength(b); //检测输入数字小数点后位数
let bigl = al>bl?al:bl,coefficient = Math.pow(10,bigl); //取大的计算系数
let tot = a * coefficient + b * coefficient //化整计算
return tot / coefficient; //返回结果
};
//减法运算 同理
let subtractionOperation = (a,b)=>{
let al = decimalLength(a),bl = decimalLength(b);
let bigl = al>bl?al:bl,coefficient = Math.pow(10,bigl);
let tot = a * coefficient - b * coefficient
return tot / coefficient;
};
一步一脚印
浙公网安备 33010602011771号