The parseInt
function in JavaScript is used to parse a string into an integer.
It can be used to convert hexadecimal, binary, or octal numbers into decimal numbers.
parseInt(string_containing_number, radix)
The parseInt
function takes in at most two arguments. The first argument is a string containing a number, and the second argument is a radix that determines the numeral system of the number present in the string.
The table below lists down the radix(s) supported by the parseInt
function:
Radix | Number System |
---|---|
2 | Binary |
8 | Octal |
10 | Decimal |
16 | Hexa-decimal |
The radix is an optional parameter. If the string starts with 0X or 0 and no radix is specified, it is assumed that the number is hexadecimal or an octal number, respectively.
The parseInt
function returns an integer, which is the integer version of the number present in the first argument.
It may also return NaN
(not a number) when:
The program below demonstrates how parseInt
is used. It converts several strings containing decimal, hexadecimal, octal and binary numbers into their integer forms.
Free Resources