Google Spreadsheet Script getValues - Force int instead of string - javascript

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?

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.

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 ?

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.

Related

Convert Ordinal String to its number

I want to Convert Ordinal String to its number
e.g
"1st" to 1
"2nd" to 2
"3rd" to 3
...
Tried this function but return its ordinal, not the number
function nth(n){return["st","nd","rd"][((n+90)%100-10)%10-1]||"th"}
it should be the inverse of this function
just use parseInt
console.log(parseInt("1st"))
You can remove the last two characters because suffix has constant length.
function toNum(str) {
return parseInt(str.substring(0, str.length - 2));
}
console.log(toNum("1st"));
Simply Extract Numerical Values From The String using parseInt()
parseInt("1st");
This will extract 1 i.e. Integer from the String
You can also use the function match(...) with a Regular Expression /[0-9]+/.
console.log("3rd".match(/[0-9]+/)[0]) // -> 3
console.log("52381st".match(/[0-9]+/)[0]) // -> 52381
Just doing "3rd".match(/[0-9]+/) returns an object with a bit of useful data, but just accessing the property [0] will give you the output you're looking for (if you don't want to do parseInt like the other answers are mentioning haha).

Is it safe to use JavaScript's Math.max on an array of strings?

This seems to work, on an array of strings that look like numbers (they're numbers from a CSV file read in with csv-parse, which seems to convert everything into strings):
var a = ['123.1', '1234.0', '97.43', '5678'];
Math.max.apply(Math, a);
Returns 5678.
Does Math.max convert strings to numbers automatically?
Or should I do a + conversion myself first to be extra safe?
Does Math.max convert strings to numbers automatically?
Quoting the ECMA Script 5.1 Specification for Math.max,
Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.
So, internally all the values are tried to convert to a number before finding the max value and you don't have to explicitly convert the strings to numbers.
But watch out for the NaN results if the string is not a valid number. For example, if the array had one invalid string like this
var a = ['123.1', '1234.0', '97.43', '5678', 'thefourtheye'];
console.log(Math.max.apply(Math, a));
// NaN
You'll get a NaN if any of the strings aren't numbers, but otherwise it should work fine. I'd add the + just to be safe.
Consider this situation:
<script>
var a=['123.1', '1234.0', '97.43', '5678','0 11111111'];
console.log(Math.max.apply(Math, a));
</script>
You need to cast elements from array to be extra safe..
if you intend to check for the max element in an array of strings using Math.max() method. you can compare the length of reach element
question: var a = ['123.1', '1234.0', '97.43', '5678'];
const checkLength = Math.max.apply(null, a.map(element => element.length));
or using spread operator for shorter form
const checkLength = Math.max(...a.map(element => element.length));
then filter to get all the elements
a.filter(elem => elem.length === checkLength)

JavaScript sort array by key?

I have an array with keys like this:
0kefsdfsdf
1101fsdf
55fdsfds
Now I want to sort that array so that the keys start with the smallest number. Afterwards the keys should look like that:
0kefsdfsdf
55fdsf
1101fsdfds
I tried this code, but its not sorting the keys:
myArray.sort(function(a, b) {
return a < b;
});
How can I sort the array according to the keys so that when I iterate the array afterwards, it starts with the key with the lowest number?
You can use
var sorted = myArray.sort(function(a,b){ return parseInt(a,10)-parseInt(b,10) });
This relies on the curious behavior of parseInt which isn't worried when asked to parse "55fdsfds" :
If parseInt encounters a character that is not a numeral in the
specified radix, it ignores it and all succeeding characters and
returns the integer value parsed up to that point. parseInt truncates
numbers to integer values. Leading and trailing spaces are allowed.

Most efficient way to retrieve numbers from a querystring?

I need to parse querystrings that contain both text and numbers. For example the following querystring:
?userID=12&team=Sales&quarter=Q1&count=2310
should be translated into the following JavaScript object:
{
userID:12, // not "12"
team:"Sales",
quarter:"Q1",
count:2310 // not "2310"
}
Currently I am doing it in two steps:
Parse the querystring
Go through all the parameters and identify which ones are numbers (either with a regex or an isNumber function !isNaN(parseFloat(n)) && isFinite(n)
This seems rather inefficient especially as most of my parameters are not numbers. Is there a better way?
do you know where are you going to use the specify value?
Because if you multiplying any string in number format like "3239" by 1 this will convert that string in number..
var example = 5 + (o.count*1) //o.count will be a number...
Two suggestions:
If you know which parameters are going to hold numbers, only do the conversion for those
The fastest way to convert strings to numbers as far as I know is to use the unary operator on them, as follows:
+(strVar)
Also multiplying by 1 is supposed to be fast AFAIK
After you parse the querystring you can convert those string representations of integer value to an actual integer like this:
var obj; // your object that the string is parsed into, with all values as strings.
for (var prop in obj) {
if (String(parseInt(obj[prop])) === obj[prop]) {
obj[prop] = parseInt(obj[prop]);
}
}

Why is the result of my calculation undefined?

when I run the javascript code below, I get the variable original as ending as
"1059823647undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined0"
why is this happening and how can i fix it?
original="012345678901234567890";
document.write("<textarea>");
document.write(original);
document.write("</textarea>"+"<br>");
/* scramble */
var scramble='1059823647';
scramble=scramble.split('');
var scrambled=new Array();
original=original.split('');
for(i=0;i<original.length;i++){
if(Math.round(Math.round(Math.floor(i/10)*10)+10)>=original.length){
scrambled[i]=original[i];
}else{
scrambled[i]=original[Math.round(Math.round(Math.floor(i/10)*10)+scramble[i%10])];
}
}
original='';
for(i=0;i<scrambled.length;i++){
original+=scrambled[i];
}
document.write("<textarea>");
document.write(original);
document.write("</textarea>"+"<br>");
undefined is being printed because your equation:
Math.round(Math.round(Math.floor(i/10)*10)+scramble[i%10])
is returning a number outside of the range of your array "original"
eg when i = 10, your equation returns 101.
I'm not entirely sure but i think what you mean to do is this:
(Math.floor(i/10)*10) + Number(scramble[i%10])
You're working with strings. But treating them like numbers. JavaScript will convert a string representation of a number to an actual number, but only when it needs to... And the + operator doesn't require such a conversion, as it acts as the concatenation operator for strings.
Therefore, this expression:
Math.round(Math.floor(i/10)*10)+scramble[i%10]
...is converting the first operand into a string and appending an element from the scramble array. You don't notice this for the first ten iterations, since when i<10 the first expression evaluates to 0... But after that, you're suddenly prefixing each scramble element with "10", and trying to access original indexes >= 100... of which there are none defined.
Solution:
Convert your strings to numbers before using them.
Math.round(Math.floor(i/10)*10)+ Number(scramble[i%10])

Categories

Resources