Javascript Number Type Conversions parseInt()

Introduction

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

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

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

The empty string returns NaN. Unlike with Number(), which returns 0.

If the first character is a number, plus, or minus, then the conversion goes on to the second character.

It 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 ignored.

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

If the first character in the string is a number, the parseInt() function recognizes the various integer formats:decimal, octal, and hexadecimal.

The string starting with "0x" is interpreted as a hexadecimal integer.

If it begins with "0" followed by a number, it is interpreted as an octal value.

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

parseInt() provides a second argument: the radix.

If you know that the value you're parsing is in hexadecimal format, pass in the radix 16 as a second argument:

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

By providing the hexadecimal radix, you can leave off the leading "0x" and the conversion will work:

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

In the code above, the radix is passed in on the first line, telling parseInt() that it will be passed a hexadecimal string.

The second line sees that the first character is not a number and stops automatically.

Passing in a radix can change the outcome of the conversion.

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



PreviousNext

Related