Google Spreadsheet Script getValues - Force int in

2019-04-23 04:59发布

问题:

Is there a way to force .getRange().getValues() to return an int? Although only numbers exist in my range, it is returning them as strings. I would like to avoid using parseInt in every one of my statements or creating a separate array with converted values.

Or is that the only solution, to get the array and then parseInt the entire array in a loop?

回答1:

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.



回答2:

You can use parseInt() or Number()

example

var A='12';var B=5
A+B = 125
parseInt(A)+B = 17
Number(A)+B = 17

That said, getValues() is not supposed to return strings unless values have some space or other non-numeric characters in it... are these values entered manually or come as a result of some function ?



回答3:

getValues() returns a 2D array of Objects - so these are Strings, Integers or Date objects depending on what these are formatted as in your spreadsheet.

Go back to your spreadsheet and see what the cells that have integer values are formatted as. Format them as integers and you should get back integers.