I'm trying to use javascript to change a string
to an int
.
var intVal = gSpread1.Text * 1;
I want intVal
's Type to be int
.
I can get an int value, if gSpread1.Text
is smaller than 1000.
But if gSpread1.Text
is larger than 1000, intVal
returns NaN
What is the correct way to use ParseInt
to ensure that it always returns an int
value?
You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.
The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
Did you try intVal = parseInt(gSpread1.Text, 10);
The 10 is called the radix, and indicate the numeral system to use.
UPDATE: There is as well a useful shortcut using the +
symbol.
eg: +gSpread1.Text
will convert the string to a number. And will return an integer
or a float
depending on the string value.
There is no int type in JavaScript. Only number. parseInt is fine if you have a non-decimal number, or you might have trailing garbage on the string like "5asdkfkasdk". But for the common case, when you know your string is only decimal digits, I prefer to use the Number() constructor. It looks more elegant and it's more familiar to C and Python programmers who do a lot of casting.
var numericValue = Number("100000");
var numericValue2 = parseInt("100000", 10);
These yield the same result of the same type.
See how to convert correctly even big numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With