前言
js
浮点数的计算存在精度不准的问题,解决方案:用整数与整数的加减乘除运算来规避该问题。
JS - 浮点数计算不精确
let [num1,num2] = [0.1, 0.2];
console.log(num1 + num2); // 0.30000000000000004
console.log(num1 - num2); // -0.1
console.log(num1 * num2); // 0.020000000000000004
console.log(num1 / num2); // 0.5
解决方案
number.js
/**
* 加 +
* @param num1
* @param num2
* @returns {number}
*/
function accAddition(num1, num2) {
const num1Digits = (num1.toString().split('.')[1] || '').length;
const num2Digits = (num2.toString().split('.')[1] || '').length;
const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
return (Math.round(num1 * baseNum) + Math.round(num2 * baseNum)) / baseNum;
}
/**
* 减 -
* @param num1
* @param num2
* @returns {number}
*/
function accSubtract(num1, num2) {
const num1Digits = (num1.toString().split('.')[1] || '').length;
const num2Digits = (num2.toString().split('.')[1] || '').length;
const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
return (Math.round(num1 * baseNum) - Math.round(num2 * baseNum)) / baseNum;
}
/**
* 乘 *
* @param num1
* @param num2
* @returns {number}
*/
function accMultiply(num1, num2) {
const num1Digits = (num1.toString().split('.')[1] || '').length;
const num2Digits = (num2.toString().split('.')[1] || '').length;
const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
return (Math.round(num1 * baseNum) * Math.round(num2 * baseNum)) / baseNum / baseNum;
}
/**
* 除 /
* @param num1
* @param num2
* @returns {number}
*/
function accDivision(num1, num2) {
const num1Digits = (num1.toString().split('.')[1] || '').length;
const num2Digits = (num2.toString().split('.')[1] || '').length;
const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
return (Math.round(num1 * baseNum) / Math.round(num2 * baseNum));
}
export {
accAddition,
accMultiply,
accSubtract,
accDivision
}
结果验证
import {accAddition, accSubtract, accMultiply, accDivision} from "@/utils/number";
let [num1,num2] = [0.1, 0.2];
console.log(accAddition(num1, num2)); // 0.3
console.log(accSubtract(num1, num2)); // -0.1
console.log(accMultiply(num1, num2)); // 0.02
console.log(accDivision(num1, num2)); // 0.5