Javascript - parseInt() function


The parseInt() function examines the string much more closely to see if it matches a number pattern.

Leading white space in the string is ignored until the first non-white space character is found.

If this first character isn't a number, the minus sign, or the plus sign, parseInt() always returns NaN, which means the empty string returns NaN.

If the first character is a number, plus, or minus, then the conversion goes on to the second character and continues on until either the end of the string is reached or a nonnumeric character is found.

For instance, "1234asdf" is converted to 1234 because "asdf" is completely ignored.

"22.5" will be converted to 22 because the decimal is not a valid integer character.

The parseInt() function recognizes the various integer formats:decimal, octal, and hexadecimal.

When the string begins with "0x", it is interpreted as a hexadecimal integer; if it begins with "0" followed by a number, it is interpreted as an octal value.

Here are some conversion examples to better illustrate what happens:

var num1 = parseInt("1234asdf");    //1234 
var num2 = parseInt("");            //NaN 
var num3 = parseInt("0xA");         //10 - hexadecimal 
var num4 = parseInt(12.5);          //12 
var num5 = parseInt("70");          //70 - decimal 
var num6 = parseInt("0xf");         //15 - hexadecimal 

parseInt() provides a second argument: the radix (number of digits) to use.

If you know that the value you're parsing is in hexadecimal format, you can pass in the radix 16 as a second argument and ensure that the correct parsing will occur, as shown here:

var num = parseInt("0xAF", 16);       //175 

In fact, by providing the hexadecimal radix, you can leave off the leading "0x" and the conversion will work as follows:

var num1 = parseInt("AF", 16);        //175 
var num2 = parseInt("AF");            //NaN 

Passing in a radix can greatly change the outcome of the conversion. Consider the following:

var num1 = parseInt("10", 2);         //2 - parsed as binary 
var num2 = parseInt("10", 8);         //8 - parsed as octal 
var num3 = parseInt("10", 10);        //10 - parsed as decimal 
var num4 = parseInt("10", 16);        //16 - parsed as hexadecimal