M Jesse
M Jesse

Reputation: 2273

Google Scripts Concatenating rather than adding

When I run my script rather than adding what I think should be two numbers, it concatenates...

I feel like I'm watching that Abbot and Costello bit. https://www.youtube.com/watch?v=9o1SAS8KyMs

  var weekNum = e.parameter.weekListBox;
  weekNum = weekNum + 3;

weekListBox has the values from 1 to 15. I am trying to offset it by 3.

However 1 + 3 yields 13, not 4 as I was expecting. Drove me nuts till I realized why this was happening.

So how do I get it to add?

Thanks

Upvotes: 1

Views: 10761

Answers (3)

M Jesse
M Jesse

Reputation: 2273

It turns out, this is the only solution that worked for me... Very strange problem.

Google Spreadsheet Script getValues - Force int instead of string

Answered by hoogamaphone

You can do this easily using the unary '+' operator as follows:

First get your values from your spreadsheet using getValue() or getValues(). Suppose you get two such values, and store them in A = 1 and B = 2. You can force them to be recognized as numbers by using any math binary operator except for +, which concatenates strings, so A - B = -1, while A + B will return '12'.

You can force the variables to be numbers simply by using the + unary operator with any variable that might be interpreted as a string. For example, +A + +B will return the correct value of 3.

Upvotes: 4

Serge insas
Serge insas

Reputation: 46792

The answer above explains the issue but does not provide a solution (except in comments but parseInt() is not the only/best solution).

The reason you have that issue is that the value returned by e.parameter.weekListBox; is actually a string (it is actually always the case except for dates which are date objects) so the result you get is the normal string concatenation (string+number=new string).

One simple solution is to change your code as follows :

  var weekNum = Number(e.parameter.weekListBox);// make it a number
  weekNum = weekNum + 3;// and the result will be a sum

Upvotes: 1

eddyparkinson
eddyparkinson

Reputation: 3700

See

function myFunction() {
    var aa = 1;
    var ab = aa + 3;

    var ba = "1";
    var bb = ba + 3;
}

ab = 4 but bb = "13"

Upvotes: -1

Related Questions