How to Use the parseInt Function in JavaScript

Posted by

How to Use the parseInt Function in JavaScript

The parseInt() function is an important tool for working with numbers in JavaScript. It allows you to take a string of text and convert it into an integer. This is useful for reading user input from forms or other sources and ensuring that you’re working with numbers instead of text. In this tutorial, we’ll cover how to use the parseInt() function in JavaScript.

Syntax

The syntax for the parseInt() function is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

parseInt(string, radix);

[/dm_code_snippet]

The first argument is the string to be converted and the second argument is the radix. The radix is the base of the number you’re trying to parse and it is an optional argument. If omitted, it will default to 10.

Examples

Let’s take a look at some examples of how to use the parseInt() function. First, let’s parse a simple string of text:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let number = parseInt("42");
// number is now equal to 42

[/dm_code_snippet]

In this example, we’re parsing the string “42” into the number 42. As the radix was omitted, JavaScript will default to base 10.

Now let’s try parsing a string with a different base:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let hexNumber = parseInt("ff", 16);
// hexNumber is now equal to 255

[/dm_code_snippet]

In this example, we’re parsing the hexadecimal string “ff” into the number 255. As the second argument is 16, JavaScript knows that we’re trying to parse a hexadecimal number.

Conclusion

The parseInt() function is a powerful tool for working with numbers in JavaScript. It allows you to take a string of text and convert it into an integer. You can also specify the radix to parse different bases of numbers. With this knowledge, you’ll be able to work with strings in your JavaScript code.