js迴圈累加以後,結尾出現很多小數

你知不知發表於2020-11-13

在js中 231242.44+281898.31+190742.02+197754.05
這樣相加以後等於901636.8200000001,為什麼會出現這麼多位小數

var sumInvoice = 0;
var sumRepairInvoice = 0;
for (let i in e) {
	sumInvoice += e[i].invoice;
	sumRepairInvoice += e[i].repairInvoice;
}
this.sumInvoice = sumInvoice;
this.sumRepairInvoice = sumRepairInvoice;

解決辦法:javascript精度的問題,浮點數只能無限接近一個值,不會具體的等於一個值。用toFixed(n)方法限制它的精度就好了。

var sumInvoice = 0;
var sumRepairInvoice = 0;
for (let i in e) {
	sumInvoice += e[i].invoice;
	sumRepairInvoice += e[i].repairInvoice;
}
this.sumInvoice = sumInvoice.toFixed(2);
this.sumRepairInvoice = sumRepairInvoice.toFixed(2);

相關文章