开发者

trying to change string -> int

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 tha开发者_开发问答t it always returns an int value?


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.


The following code works for me:

var intVal = parseInt("100000");
alert(intVal);

Perhaps post your non-working code? The issue might lie elsewhere.


If you are sure that your string contains int you can use just one +

var n = "455";
n = +n; // now n is integer
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜