Domanda

When adding numbers which I pull off a CSV, this is the logfile I am getting:

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);

Here is the log, is goes well until the 3rd, where I get a strange rounding error:

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

Why is this happening?

Kind regards, Riel

È stato utile?

Soluzione

Floating point arithmetic is prone to rounding errors in javascript and apps-script. See Is floating point math broken?. You'll also find a very complete overview, including solutions, here, notably the section on Euros or Cents.

To demonstrate, I've modified your code to shift the decimal point:

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);
  }
} 

Here's the logs from that - I think they look like you expected them to.

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

Some people advocate performing all monetary calculations using integers, to eliminate rounding errors. Javascript and apps-script don't have integer as a type, just number. You can still do your calculations in "cents", and leave the expression of "dollars" / "Euros" as a display function.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top