前言:在日常做项目中,有时候会碰到需要计算金额,这个时候如果你碰到了0.1+0.2这样的,会得到一个0.30000000000000004这样的结果,是不是很懵逼。事实上这是因为js在处理浮点数上是有问题的,下面我分享一个能处理js小数四则运算的函数。
//科学运算(解决js处理浮点不正确的问题)
//num1(要进行运算的第一个数字)
//operator(运算符号,+,-,*,/)
//num2(要进行运算的第二个数字)
/*
测试例子:
console.log(0.1 + 0.2, computed(0.1, '+', 0.2));
console.log(19044.009 + 0.01, computed(19044.009, '+', 0.01));
console.log(19044.002 - 0.01, computed(19044.002, '-', 0.01));
console.log(19044.003 * 0.05, computed(19044.003, '*', 0.05));
console.log(19044.001 / 0.05, computed(19044.001, '/', 0.05));
console.log(11 + 22, computed(11, '+', 22));
*/
function computed(num1, operator, num2) {
var numArr1 = (num1 + '').split('.');
var numArr2 = (num2 + '').split('.');
var numArr11 = numArr1[1] || 0;
var numArr21 = numArr2[1] || 0;
var length1 = numArr11 ? numArr11.length : 0;
var length2 = numArr21 ? numArr21.length : 0;
var integer1 = Math.pow(10, length1);
var integer2 = Math.pow(10, length2);
var iMax = Math.max(integer1, integer2);
var diffInteger1 = iMax / integer1;
var diffInteger2 = iMax / integer2;
var decimals1 = +numArr11 * diffInteger1;
var decimals2 = +numArr21 * diffInteger2;
var result = '';
num1 = numArr1[0] * iMax + decimals1;
num2 = numArr2[0] * iMax + decimals2;
switch (operator) {
case '+':
result = (num1 + num2) / iMax;
break;
case '-':
result = (num1 - num2) / iMax;
break;
case '*':
result = (num1 * num2) / (iMax * iMax);
break;
case '/':
result = num1 / num2;
break;
}
return result;
}