The parseInt() method takes two parameters. The first one is the string you want to convert to an integer and is required.
The second parameter, called the “radix,” is optional. It represents the radix in which your value appears that is required for your conversion.
The radix argument is not as commonly used as the last one. In most cases, your numbers will be formatted in 10 decimal. The default radix is 10 decimal so you do not need to worry about this argument.
You can include spaces at the start and end of a value that you want to convert to a number. But, spaces in the middle of a number are not allowed.
If you try to parse a value that includes letters, you will receive a NaN value. The radix argument may let you include some letters, such as “x” in your number. This is only the case where the letter is relevant to how a number is formatted.
Let’s use an example to illustrate how this works. Let’s say that we have a string “20202” that we want to convert to an integer. We could do so using the following code:
The parseInt() function parses a string and returns an integer as follows:
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
Similarly, if we use the “radix” argument, we can convert our numbers to strings in different bases.
The “radix” argument takes in a number between 2 and 36 and describes the numerical system the parseInt() function should use. Say we want to convert a “15” from hexadecimal that has a radix value of “16.” We could do so using the following code:
Our function returns:
Passing Invalid Values to parseInt()
which stands for Not a Number. Here’s an example of using
into a string:
Our number parseInt returns
string characters cannot be converted into a number.