Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to change string -> int

Tags:

javascript

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?

like image 806
Sungguk Lim Avatar asked Feb 24 '10 00:02

Sungguk Lim


People also ask

How do you change a string to a number?

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.

How do you change a character in a string to an integer?

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.

How do you change a string to an int in C++?

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.


3 Answers

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.

like image 187
Mic Avatar answered Oct 20 '22 07:10

Mic


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.

like image 28
jpsimons Avatar answered Oct 20 '22 08:10

jpsimons


See how to convert correctly even big numbers.

like image 31
Sarfraz Avatar answered Oct 20 '22 06:10

Sarfraz