Corsi registrati su
Corsi in diretta per la formazione di Front End Developer e Back End Developer
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.
Examples with the first parameter, the string.
it returns isNaN as it fails to do the conversion. But if for example I write:
It returns me 13 as it can read the first few characters.
If instead I indicate:
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.
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.
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.
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));
Some useful links