2013-01-09 148 views
0

變量添加號碼如果加入,我拉過一個CSV數字,這就是我得到的日誌文件:在谷歌Apps腳本會奇怪

var costs = Number(csvData[i][9].replace(",",".")); // need to replace , with . and  
total_costs_overeenkomst=total_costs_overeenkomst+costs; // add variables 
Logger.log("Kosten: "+costs); 
Logger.log("Subtotaal:"+total_costs_overeenkomst); 

這裏是日誌,是順利的話,直到3日,我得到一個奇怪的舍入誤差:

Kosten:4.8 
Subtotaal:4.8 
Kosten:49.92 
Subtotaal:54.72 
Kosten:4.8 
Subtotaal:59.519999999999996 
Kosten:2.4 
Subtotaal:61.919999999999995 
Kosten:2.57 
Subtotaal:64.49 
Kosten:22.18 
Subtotaal:86.66999999999999 
Kosten:34.56 
Subtotaal:121.22999999999999 
Kosten:4.8 
Subtotaal:126.02999999999999 

爲什麼會發生這種情況?

親切的問候, 瑞爾

回答

1

浮點運算是容易四捨五入JavaScript和應用程序腳本錯誤。見Is floating point math broken?。您還可以找到非常全面的概述,其中包括解決方案here,特別是Euros or Cents的部分。

爲了證明,我已經修改了你的代碼到小數點移位:

function calcCosts() { 
    var csvData = ["4,8","49,92","4,8","2,4","2,57","22,18","34,56","4,8"]; 
    var total_costs_overeenkomst = 0; 

    for (i in csvData) { 
    var costs = Number(csvData[i].replace(",",".")); // need to replace , with . and  
    total_costs_overeenkomst=(100*total_costs_overeenkomst+100*costs)/100; // add variables 
    Logger.log("Kosten: "+costs); 
    Logger.log("Subtotaal:"+total_costs_overeenkomst); 
    } 
} 

下面是從日誌 - 我認爲他們看起來像你期望他們。

Kosten: 4.8 
Subtotaal:4.8 
Kosten: 49.92 
Subtotaal:54.72 
Kosten: 4.8 
Subtotaal:59.52 
Kosten: 2.4 
Subtotaal:61.92 
Kosten: 2.57 
Subtotaal:64.49 
Kosten: 22.18 
Subtotaal:86.67 
Kosten: 34.56 
Subtotaal:121.23 
Kosten: 4.8 
Subtotaal:126.03 

有些人主張使用整數執行所有貨幣計算,以消除舍入誤差。 Javascript和應用程序腳本沒有integer作爲一種類型,只是number。您仍然可以按「美分」進行計算,並將「美元」/「歐元」的表達作爲顯示功能。