0

添加我从 CSV 中提取的数字时,这是我得到的日志文件:

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

为什么会这样?

亲切的问候,瑞尔

4

1 回答 1

1

浮点运算在 javascript 和 apps-script 中容易出现舍入错误。请参阅浮点数学是否损坏?. 您还可以在此处找到非常完整的概述,包括解决方案,特别是有关欧元或美分的部分。

为了演示,我修改了您的代码以移动小数点:

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 和 apps-script 没有integer作为类型,只是number. 您仍然可以以“美分”进行计算,并将“美元”/“欧元”的表达式保留为显示函数。

于 2013-01-30T11:49:43.113 回答