Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Global Functions and Values

The parseInt() function

Reference for JavaScript parseInt(): converting strings to integers, the radix argument, partial parsing, NaN results and how it differs from Number().

parseInt() reads a string from the left and returns the integer it finds there. It stops at the first character that cannot be part of a number, so "42px" becomes 42. If the string does not start with a number at all, the result is NaN.

The function is the same object as Number.parseInt. It exists mainly for text that carries a number plus something else, such as CSS values or user input with units.

JavaScript
parseInt("42px");      // 42
parseInt("ff", 16);    // 255

Try it

JS Parsing integers

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

No output.

JS Why you should pass a radix

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

No output.

Syntax

JavaScript
parseInt(string)
parseInt(string, radix)
Name Description
string The value to parse. Anything that is not a string is converted to one first. Leading whitespace is ignored.
radix Optional integer from 2 to 36 giving the base of the number. If omitted or 0, the base is 10, except that a 0x or 0X prefix selects 16.

Return value: an integer, or NaN if the first non-whitespace characters cannot form a number. A radix outside 2 to 36 also gives NaN.

Exceptions: none for ordinary values. A Symbol, or an object whose string conversion throws, causes a TypeError or the thrown error.

Usage notes

  • Always pass the radix (usually 10). The default is predictable in modern engines, but an explicit radix makes the intent clear and avoids the hexadecimal surprise for strings that start with 0x.
  • Partial parsing is a feature and a trap. parseInt("12abc") is 12, which can hide bad input. When the whole string must be a number, use Number() or check with Number.isInteger(Number(text)).
  • It truncates toward zero. parseInt("-3.9") is -3. For rounding use Math.round(), Math.floor() or Math.trunc() on a number instead.
  • A sign is allowed, one + or - directly before the digits. Digits only valid in the radix count: parseInt("19", 8) is 1.
  • Non-strings are converted first. Passing a number such as 0.0000005 converts it to the string "5e-7" and returns 5. Do not use parseInt() to round numbers.
  • No numeric separators or binary/octal prefixes. "1_000" gives 1, and "0b11" gives 0 (the parser stops at b).
  • Large values lose precision beyond Number.MAX_SAFE_INTEGER. Use BigInt("...") for exact big integers.
  • Using it as a callback is a classic bug: ["1", "2", "3"].map(parseInt) passes the index as the radix and returns [1, NaN, NaN]. Write .map(s => parseInt(s, 10)) or .map(Number).

Browser support

parseInt() is available in every browser and JavaScript runtime.