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:
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()
“NaN,” which stands for Not a Number. Here’s an example of using
parseInt() to convert
“Hey” into a string:
Our number parseInt returns
“NaN,” because the
“Hey” string characters cannot be converted into a number.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Read more