0

I have developed a simple script to calculate the sum of the numerical values of an array Sheet

Here is the Sheet array

And here is the associated code:

function test() {
var classeur = SpreadsheetApp.getActiveSpreadsheet();
var feuille = classeur.getSheetByName('test');
var tPoidsBrut = feuille.getRange("D1:D16").getValues();
var sommePoidsBrut = 0;
for (let i = 0; i < tPoidsBrut.length; i ++){
  if(Number(tPoidsBrut[i] != 0)){
    var sommePoidsBrut = sommePoidsBrut + Number(tPoidsBrut[i]);
  }
}
Logger.log(sommePoidsBrut);
}

The problem I have is the following. When I add the values from D1 to D15, everything works correctly. However, when I add the value A16, it returns a sum that does not correspond to what I expect (screenshot below).

screenshot of Logger.log

As you can see, it finds me 13987.199999999999 instead of 13987.2. I don't know where this micro deviation comes from, knowing that in D16, I add 1147.8 (I checked and it is indeed this number that is added). If I add a decimal number other than this one, it is not a problem and the calculation is correct.

Do you know where this problem could come from? Thanks in advance for your feedback.

Damien
  • 87
  • 5

1 Answers1

0

It's a duplicate issue, please refer to this answer.

You have this kind of rounding errors in all languages because they work in the binary system whereas we expect them to give accurate decimal results. This sometimes causes this kind of trouble, but can be handled.

Dmitry Kostyuk
  • 1,354
  • 1
  • 5
  • 21