The parseInt() Method in JavaScript
In this blog post, we will explore the parseInt() method of the Number object in JavaScript. The parseInt() method is used to parse a string argument and convert it into an integer number. Let’s take a closer look at how it works and its various use cases.
Basic Usage
The parseInt() method can be used with a string argument, and it will return the parsed integer value. Here are some examples:
1 | Number.parseInt('10') // 10 |
As demonstrated above, the parseInt() method is quite flexible. It can convert strings with numeric values into integers, even if they contain non-numeric characters. The method extracts the first number from the string.
Handling Non-numeric Strings
If the string does not begin with a number, the parseInt() method will return NaN (Not a Number). For example:
1 | Number.parseInt('I am Flavio and I am 36') // NaN |
Specifying Radix
The parseInt() method also accepts a second parameter, which specifies the radix or base of the number being converted. By default, the radix is 10 (decimal). However, you can use other radices for octal or hexadecimal conversions. Here are some examples:
1 | Number.parseInt('10', 10) // 10 |
In the third example, the radix is set to 8 (octal), resulting in the number 8 being parsed instead of 10.
In summary, the parseInt() method in JavaScript is a powerful tool for converting string values into integers. It handles a wide range of scenarios and also allows you to specify the radix for different number systems. Make sure to utilize this method effectively in your JavaScript projects.
tags: [“JavaScript”, “parseInt”, “Number”, “radix”]