Number.parseInt()

Converts the start of a string into an integer in a given numeral system.

Returns
An integer, or NaN.
On this page

Example

#
JavaScript
console.log(Number.parseInt('42px', 10))
console.log(Number.parseInt('3.99', 10))
console.log(Number.parseInt('ff', 16))
console.log(Number.parseInt('abc', 10))
Console
42
3
255
NaN

Definition and usage

#

The Number.parseInt(text, radix) function reads a string from the left and converts its start into an integer. It stops at the first character that doesn’t fit, so "42px" gives 42. If the first character isn’t a digit, the result is NaN.

The second argument is the base of the numeral system: 10 for decimal, 16 for hexadecimal, 2 for binary. Always provide it to avoid surprises.

This is the same function as the global parseInt(). To convert an entire string into a number, without truncating the end, Number() is usually the better choice.

Syntax

#
Syntax
Number.parseInt(string)
Number.parseInt(string, radix)

Parameters

#
  • string

    string

    The text to process. Leading whitespace is skipped.
  • radix

    number 2-36, optional

    The base of the numeral system. Always provide it, usually 10.

More examples

#
parseInt() vs. Number()
JavaScript
console.log(Number.parseInt('12abc', 10))
console.log(Number('12abc'))
console.log(Number(''))
console.log(Number.parseInt('', 10))
Console
12
NaN
0
NaN

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Always provide the second argument, for example parseInt(value, 10).
  • For validating form data, Number() is better, since it rejects a string with a non-matching tail.

Related entries

#

Spotted a mistake or missing an example? Write to us.