【前端填坑】累加含小数点的数据:parseFloat、toFixed等
-
<script type="text/javascript">
-
//要求:累加含有两位小数点的数据
-
var numbs = ['545.6','172.95','936.93','200','43.2','202.65','8573.9','171.92','72.69',
-
'280','662.11','12.6'];
-
-
//出错方法:
-
var amount = 0;
-
for(var i = 0;i < 12;i++){
-
amount += parseFloat(numbs[i]);
-
}
-
console.log("直接使用parseFloat计算结果:"+amount);//11874.550000000001
-
-
//方案一:通过parseFloat累计,然后再使用toFixed进行四舍五入
-
var amount1 = 0;
-
for(var i = 0;i < 12;i++){
-
amount1 += parseFloat(numbs[i]);
-
}
-
console.log("toFixed计算结果:"+amount1.toFixed(2));//11874.55
-
-
//方案二:通过乘以100,再除以100.这样可以将var类型转换成number类型
-
var amount2 = 0;
-
for(var i = 0;i < 12;i++){
-
amount2 += numbs[i] * 100;
-
}
-
amount2 = amount2 / 100;
-
console.log("*100/100计算结果:" + amount2);//11874.55
-
-