JavaScript parseInt()

The parseInt() function parses a string argument and returns an integer of the specified radix.

Example

const stringDate = "1996";

// parse the string to decimal let intDate = parseInt(stringDate, 10);
console.log(intDate) // Output: 1996

parseInt() Syntax

The syntax of the parseInt() function is:

parseInt(string, radix)

parseInt() Parameters

The parseInt() function takes in:

  • string - The value to parse. If it is not a string, it is converted to one using ToString abstract operation.
  • radix (optional) - An integer between 2 and 36 representing the base in the numeral system.

parseInt() Return Value

  • Returns an integer parsed from the given string.
  • Returns NaN when:
    • radix is less than 2 or greater than 36.
    • The first non-whitespace character can't be converted to a number.

Example: Using parseInt()

console.log(parseInt("875.99", 10)); // 875

console.log(parseInt("F", 16)); // 15
console.log(parseInt("0xF")); // 15 -> JavaScript consider 0x... to be hexadecimal
console.log(parseInt("-17", 8)); // -15 // int is detected till a non-numeric character console.log(parseInt("85,123", 10)); // 85
console.log(parseInt("FXX123", 16)); // 15
console.log(parseInt("45", 13)); // 57 console.log(parseInt("Hello", 8)); // NaN
console.log(parseInt("546", 2)); // NaN -> Invalud as binary has only 1 or 0
// BigInt values lose precision console.log(parseInt("464546416543075614n")); // 464546416543075600

Output

875
15
15
-15
85
15
57
NaN
NaN
464546416543075600

Note: If the radix parameter is undefined, 0, or unspecified, JavaScript considers the following:

  • If the string begins with "0x", the radix is 16 (hexadecimal).
  • If the string begins with "0", the radix is 8 (octal) or 10 (decimal). The exact radix chosen is implementation-dependant
  • If the string begins with any other value, the radix is 10 (decimal).

Recommended Reading: Javascript parseFloat()

Did you find this article helpful?