JS关于小数之间的计算
/**
* calc.plus 加法运算
* calc.subtract 减法运算
* calc.multiply 乘法运算
* calc.divide 除法运算
*/
var calc = (function () {
let operation = (num1, num2, op) => {
let l1, l2, max;
try {
l1 = num1.toString().split(".")[1].length;
} catch (e) {
l1 = 0;
}
try {
l2 = num2.toString().split(".")[1].length;
} catch (e) {
l2 = 0;
}
switch (op) {
case "plus":
max = Math.pow(10, Math.max(l1, l2));
return (num1 * max + num2 * max) / max;
case "subtract":
max = Math.pow(10, Math.max(l1, l2));
return (num1 * max - num2 * max) / max;
case "multiply":
return (Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", ""))) / Math.pow(10, l1 + l2);
case "divide":
return operation(Number(num1.toString().replace(".", "")) / Number(num2.toString().replace(".", "")), Math.pow(10, l2 - l1), "multiply");
}
};
let plus = (a, b) => {
return operation(a, b, "plus");
};
let subtract = (a, b) => {
return operation(a, b, "subtract");
};
let multiply = (a, b) => {
return operation(a, b, "multiply");
};
let divide = (a, b) => {
return operation(a, b, "divide");
};
return { plus, subtract, multiply, divide };
})();
console.log(0.1 + 0.2, calc.plus(0.1, 0.2));
//输出:0.30000000000000004 0.3
console.log(0.2 + 0.4, calc.plus(0.2, 0.4));
//输出:0.6000000000000001 0.6
console.log(1.0 - 0.9, calc.subtract(1.0, 0.9));
//输出:0.09999999999999998 0.1
console.log(0.9 - 0.7, calc.subtract(0.9, 0.7));
//输出:0.20000000000000007 0.2
console.log(19.9 * 100, calc.multiply(19.9, 100));
//输出:1989.9999999999998 1990
console.log(79.9 * 100, calc.multiply(79.9, 100));
//输出:7990.000000000001 7990
console.log(6.6 / 0.2, calc.divide(6.6, 0.2));
//输出:32.99999999999999 33
console.log(99.9 / 3, calc.divide(99.9, 3));
//输出:33.300000000000004 33.3