前端计算金钱类的算数
1.js的数据类型中只有number,计算时如果数字中含有小数点就会出错,所以需要进行处理
addNumber(num1, num2) {
var p1 = 0; var p2 = 0;
if (num1.toString().split('.').length > 1) {
p1 = num1.toString().split('.')[1].length;
}
if (num2.toString().split('.').length > 1) {
p2 = num2.toString().split(".")[1].length;
}
var p = p1 > p2 ? p1 : p2;
var n1 = num1 * Math.pow(10, p);
var n2 = num2 * Math.pow(10, p);
var result = (n1 + n2) / Math.pow(10, p);
return result;
},
将需要的数字传入,即可。