遍历data中test,并累加、算总数
let a = [351.8,351.8,351.8,351.8,351.8,351.8,521,421.6,299.1,295.7,670.7,851.7]
console.log(a)
//定义
let sum = 0;
a.forEach((item) => {
sum = this.numAdd(sum,item) // 数字叠加会出现精度丢失的问题,所以得通过以下方法配合
});
console.log('sum',sum)
// 结果5170.6
// 数字累加
numAdd(num1, num2) {
var baseNum, baseNum1, baseNum2;
try {
baseNum1 = num1.toString().split(".")[1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split(".")[1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
return (num1 * baseNum + num2 * baseNum) / baseNum;
}
网友评论