Google Apps Script Concatenating Numbers Rather Than Adding
I wrote the code below to grab a portion of a column of numbers and add them up. However, the function is concatenating numbers rather than adding. I'm getting this result: 0AMOUNT
Solution 1:
Your result is the hint: That's not a number being added. That's strings being concatenated.
currAmount = sheet.getRange(k, startColumn).getValue();
sum += currAmount; //currAmount + sum;
Specifically, this is the main problem. Regardless of whether the number returned by getValue()
is a number or not, you add it to sum
.
A few ways to fix this would be to adjust the value of k
, to check the typeof
the value, or coerce the value into a number, depending on exactly what you're trying to do. This is essentially a javascript problem, with the canonical answer here
Also, generally you should batch operations where possible; e.g., instead of running getRange().getValue()
every go through a for-loop, you are much better using (as an example, may need tweaking)
var amounts = sheet.getRange(startMonth, startColumn, (lastRow - startMonth), 1);
for(var k = startMonth; k <= lastRow; k++){
sum += amounts[k][0]
Logger.log(sum);
}
Post a Comment for "Google Apps Script Concatenating Numbers Rather Than Adding"