Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Number and BigInt

Number.parseInt()

Reference for Number.parseInt(): parsing integers from strings in any radix from 2 to 36, partial parsing, hex prefixes, NaN results and common pitfalls.

Number.parseInt() reads a string from the left and returns the integer it finds there, in the number base you choose with the second argument. It skips leading whitespace, accepts an optional sign and stops at the first character that is not a valid digit for the base. If no digits are found, the result is NaN.

It is the same function object as the global parseInt(). Always pass the radix explicitly so the result does not depend on the string's prefix.

JavaScript
Number.parseInt(string, radix)

Try it

JS Parsing in different bases

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Pitfalls with numbers and map()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Number.parseInt(string)
Number.parseInt(string, radix)
Name Description
string The value to parse. Non-strings are converted to a string first.
radix Optional integer from 2 to 36: the base of the number in string. If it is omitted or 0, base 10 is used, except that a 0x or 0X prefix selects base 16. Any other value outside 2-36 gives NaN.

Return value: an integer, or NaN if no digits could be read.

Exceptions: none for ordinary values; a Symbol throws a TypeError.

Usage notes

  • Always pass a radix. parseInt(text, 10) says what you mean and avoids the 0x surprise.
  • It truncates. parseInt("3.99") is 3. To round, use Math.round(Number(text)); to parse a decimal, use parseFloat().
  • Do not use it to floor numbers. parseInt(0.0000005) is 5 because the number is converted to the string "5e-7" first. Use Math.trunc() or Math.floor().
  • Trailing text is ignored. "42px" gives 42. For strict validation use Number(text) together with Number.isInteger().
  • map(parseInt) is a bug, because the index becomes the radix. Pass an arrow function or use Number.
  • Letters as digits: for radix above 10, letters a-z (case-insensitive) stand for 10-35.
  • Precision: results above Number.MAX_SAFE_INTEGER may be rounded. Use BigInt("123...") for exact huge integers.
  • Empty or whitespace-only input is NaN, unlike Number("") which is 0.
  • Modern code often uses Number() for whole strings, and parseInt() only when the text has a suffix or a non-decimal base.

Browser support

Supported in all current browsers. The Number.parseInt alias arrived with ES2015, and the global function has existed since the beginning.