Number. parseInt()
Converts the start of a string into an integer in a given numeral system.
- Returns
- An integer, or
NaN.
Example
#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))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
#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
#console.log(Number.parseInt('12abc', 10))
console.log(Number('12abc'))
console.log(Number(''))
console.log(Number.parseInt('', 10))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
#- Number.parseFloat()Converts the start of a string into a floating-point number.
- Number.isNaN()Checks whether a value is exactly NaN.
- Number.isInteger()Checks whether a value is an integer.
- Math.trunc()Cuts off the fractional part of a number, leaving the integer part.
- Number.prototype.toString()Converts a number into a string, also in a different numeral system, e.g. binary or hexadecimal.
Spotted a mistake or missing an example? Write to us.