Google Apps脚本连接数字而不是添加数字 [英] 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.
我得到这个结果:
0AMOUNT120123126129132135138141144147
但是,如果我从12月开始运行,其总和应为: 432
But if I run it from Dec on the sum should be: 432
我在Google脚本中的代码:
My code in Google Scripts:
//add sum and input it into the total column
function sum(startMonth, startColumn, lastRow){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
startColumn = startColumn +1;
var sum = 0;
var currAmount = 0;
var k = 0;
for(k = startMonth; k <= lastRow; k++){
currAmount = sheet.getRange(k, startColumn).getValue();
sum += currAmount; //currAmount + sum;
Logger.log(sum);
}
SpreadsheetApp.getActiveSheet().getRange(k, startColumn).setValue(sum);
SpreadsheetApp.getActiveSheet().getRange(k, startColumn).setBackground("Yellow");
return sum;
}
以及我的工作表的快照:
And a snapshot of my sheet:
推荐答案
您的结果是提示:这不是要添加的数字.字符串被串联了.
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;
具体地说,这是主要问题.不管getValue()
返回的数字是否为数字,都可以将其添加到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
.
解决此问题的几种方法是调整k
的值,检查typeof
的值或将值强制转换为数字,具体取决于您要执行的操作.这本质上是一个JavaScript问题,使用标准答案
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
此外,通常,您应该批量操作 ;例如,与其使用getRange().getValue()
进行遍历循环,不如使用它更好(例如,可能需要进行调整)
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);
}
这篇关于Google Apps脚本连接数字而不是添加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!