function Calculation(type, num1, num2) {

var temp1, temp2, a;
try {
// 获取temp1小数点后的长度
temp1 = num1.toString().split(".")[1].length;
}
catch (e) {
temp1 = 0;
}
try {
// 获取temp2小数点后的长度
temp2 = num2.toString().split(".")[1].length;
}
catch (e) {
temp2 = 0;
}
// Math.max(temp1, temp2) 为了获取temp1和temp2两个值中较大的一个
// Math.pow(a,b) 表示 a 的 b 次方
a = Math.pow(10, Math.max(temp1, temp2));

// 计算的方式是先将所有的小数乘为整数,待加减运算执行完之后再除去对应的 a 的值,将其变为小数输出
// 先判断执行的方式是否是加法,不是的话则执行减法运算
return type == "add" ? (num1 * a + num2 * a) / a : (num1 * a - num2 * a) / a;
}

var temp = Calculation('reduce',0,0.05);// 执行减法运算
console.log(temp);// 输出结果是 -0.05
————————————————
版权声明:本文为CSDN博主「杉杉up」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39501040/article/details/102922031