The JavaScript parseInt() function

Definition and usage

parseInt() The function parses the string and returns an integer.

radix The parameter is used to specify which number system to use, for example, a base of 16 (hexadecimal) means that the numbers in the string should be parsed as decimal numbers from the hexadecimal number.

If radix The parameter is omitted, and JavaScript assumes the following:

  • If the string starts with "0x", the base is 16 (hexadecimal).
  • If the string starts with "0", the base is 8 (octal). This feature is deprecated.
  • If the string starts with any other value, the base is 10 (decimal).

Note:It only returns the first number in the string!

Note:Leading and trailing spaces are allowed.

Note:If the first character cannot be converted to a number,parseInt() Returns NaN.

Note:Old browsers will cause parseInt("010") to be 8, because old versions of ECMAScript (older than ECMAScript 5) use octal base (8) as the default value when a string starts with "0". From ECMAScript 5 onwards, the default value is decimal base (10).

Example

Parsing different strings:

var a = parseInt("10") + "<br>";
var b = parseInt("10.00") + "<br>";
var c = parseInt("10.33") + "<br>";
var d = parseInt("34 45 66") + "<br>";
var e = parseInt(" 60 ") + "<br>";
var f = parseInt("40 years") + "<br>";
var g = parseInt("He was 40") + "<br>";
var h = parseInt("10", 10)+ "<br>";
var i = parseInt("010")+ "<br>";
var j = parseInt("10", 8)+ "<br>";
var k = parseInt("0x10")+ "<br>";
var l = parseInt("10", 16)+ "<br>";
var n = a + b + c + d + e + f + g + "<br>" + h + i + j + k + l;

Try it yourself

Syntax

parseInt(string, radix)

Parameter value

Parameter Description
string Required. The string to be parsed.
radix Optional. Represents the number system to be used by the number (from 2 to 36).

Technical Details

Return Value: Returns a number. If the first character cannot be converted to a number, it returns NaN.
JavaScript Version: ECMAScript 1

Browser Support

Function Chrome Edge Firefox Safari Opera
parseInt() Support Support Support Support Support