Javascript 从谷歌应用程序脚本中的变量添加数字

Javascript 从谷歌应用程序脚本中的变量添加数字,javascript,google-apps-script,rounding-error,Javascript,Google Apps Script,Rounding Error,当添加我从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:"+tot

当添加我从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
为什么会这样

亲切问候,,
Riel

浮点运算在javascript和应用程序脚本中容易出现舍入错误。看见您还将看到一个非常完整的概述,包括解决方案,特别是关于

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

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
。您仍然可以使用“美分”进行计算,并保留“美元”/“欧元”的表达式作为显示功能