myGlobal.parseInt( string, [ radix ] ) in ECMAScript 262
Attempt to convert a string into an integer number, using the specified base.
Arguments
name | type | description |
---|---|---|
string | String | The string to convert to a num |
radix | Number |
[optional]
The base for the conversion. |
- Return Type
- Number
Description
In most cases, var strAsNum = myStr*1;
or var strAsnum = +myStr;
are more appropriate than using var strAsNum = parseInt(myStr,10)
. (And they're faster, too.)
Although radix
is not required, it should not be omitted. This is because when omitted, it takes on one of three values, depending on the string:
- The radix starts out at base 10.
- If the first character is a '0', it switches to base 8.
- If the next character is an 'x', it switches to base 16.
Given the above, parseInt('11')
returns 11, while parseInt('011')
returns 9. Because of this, you should always specify your desired base (usually 10) when parsing input from a user.
Unlike an implicit (and faster) conversion to a number by multiplying a value by 1 (e.g. var x='17'; x=x*1;
), parseInt
reads up to the first character which does not fit the specified radix
, and ignores the rest. See the following example for the implications of this:
var userInput1 = "$1,000";
var userInput2 = "1,000";
var userInput3 = " 15zzzzz";
var userInput4 = "1.34";
var val1,val2,val3,val4;
val1 = userInput1*1; //NaN -- bad characters found
val1 = parseInt(userInput1,10); //NaN -- no valid characters found before invalid ones
val2 = userInput2*1; //NaN -- bad characters found
val2 = parseInt(userInput2,10); //1 -- the user meant "1000", but the script turned it into just "1", stopping at the comma
val3 = userInput3*1; //NaN -- bad characters found
val3 = parseInt(userInput3,10); //15 -- leading spaces are ignored, and the conversion stops at the first 'z'
val4 = userInput4*1; //1.34
val4 = parseInt(userInput4,10); //1 -- the conversion stopped when it hit the decimal. See parseFloat
Despite the above, this function has its uses in user interaction, and is the only way to convert a string into a number using a base other than 10.
var x = parseInt('01011',2); //11
var y = parseInt('ff',16); //255