方法:
// 运算
// num1: 第一个数, num2: 第二个数, symbol: 符号(+-*/)
amend: function(num1, num2, symbol) {
if (!num1) num1 = 0;
if (!num2) num2 = 0;
var str1 = num1.toString(),
str2 = num2.toString(),
result, str1Length, str2Length
//解决整数没有小数点方法
try {
str1Length = str1.split('.')[1].length
} catch (error) {
str1Length = 0
}
try {
str2Length = str2.split('.')[1].length
} catch (error) {
str2Length = 0
}
var step = Math.pow(10, Math.max(str1Length, str2Length))
switch (symbol) {
case "+":
result = (num1 * step + num2 * step) / step
break;
case "-":
result = (num1 * step - num2 * step) / step
break;
case "*":
result = ((num1 * step) * (num2 * step)) / step / step
break;
case "/":
result = (num1 * step) / (num2 * step)
break;
default:
break;
}
return result
},
调用:
amend(5, 1, '-'); //输出为4