The JavaScript parseInt function is generally used to convert its first argument to an integer.

The syntax is therefore the following: parseInt(string, root).

Where string represents the string to convert, while the root parameter is optional.

The root parameter is used to specify which numbering system to use for the conversion and can have a value from 2 to 36. So it can be for example 16 (hexadecimal), 8 (octal), 2 (binary), etc. If this parameter is omitted then, if the string starts with ‘0x’ the root is hexadecimal, if the string starts with ‘0’ then the root is octal, instead if the string starts with another character it tries to convert the string to decimal .

When the conversion cannot take place, the function indicates that it is not a number by returning isNaN.

JavaScript parseInt examples

Examples with the first parameter, the string.

Let’s take examples of using the parseInt () function in JavaScript.



parseInt("coding creativo");

it returns isNaN as it fails to do the conversion. But if for example I write:



parseInt("13coding creativo");

It returns me 13 as it can read the first few characters.

If instead I indicate:



parseInt("coding creativo13");

in this case it always returns isNaN because it doesn’t see the number written at the end of the string.

If as the first parameter I pass a number with a comma, or a time, a date or a number with blank spaces, as in the examples below:



parseInt ("13.50");
parseInt ("13:50");
parseInt ("01-13-20");
parseInt ("13 01 20");

I’ll have as a result an integer, in our case 13.

Banner pubblicitario

Examples of using parseInt JavaScript with the first and second parameters, that is, the string and the root

Let’s now make some examples where we also pass the root.

For example, we insert the binary number 1101 as a string and then insert the corresponding base. The function will return me the integer 13.



parseInt("1101", 2);

Similarly if we use the other bases, such as 16 and 8, the function will return me the corresponding decimal number:



parseInt ("13", 16);
parseInt ("13", 8);

In the first example we get 19, while in the second we get 11.

Examples of using parseInt JavaScript with the prompt or input box

One of the most common uses, also presented in many examples in this tutorial, is through a command prompt or via the input box. Here is an example of use with the prompt:

var number = parseInt (prompt (Insert a number));

Conclusion

In this lesson we studied the parseInt function of JavaScript and we studied some examples of use, in the next lessons we will see some practical applications.

Some useful links

Indice argomenti tutorial JavaScript