The parseInt() is a function to which we can pass a string as an argument and it will return us an integer if it exists.
This function returns NaN(Not a Number). If, no number found in that string. This function also returns NaN if there exists any character before the number.
Let’s take a look at the syntax of the parseInt() function.
parseInt(value [, base]);
Value is the string that we want to parse into the integer.
And the base is the base number of the provided string to which we want to convert into a decimal number. It is an optional value.
Let’s have look at a couple of examples to understand more clearly.
parseInt(“34”); // 34</td>
Now, let’s try to give a float number.
As you can see. It only prints the 34.
Let’s try to put a space before or after the number.
It worked fine.
But, if we put any character before the number.
parseInt(“the 34”); // NaN
It prints NaN(Not a Number). The same applies to the empty string.
Now, what if we try to give the base number along with the value. Like, the base of the binary number system is 2.
parseInt(“34”, 2); // NaN
Ok, since 3 and 4 are not the numbers of a binary number system. It prints NaN.
Now if we provide it a true binary number. It should print the decimal number against that binary number.
parseInt(“10011011”, 2); // 155
Here comes an interesting thing about this function. Like, if we keep on providing the binary number 0’s and 1’s. It will keep on converting that number into the decimal number system. But, when we start to give a non-binary number system. It will stop right there and won’t convert any further. But, until we keep on giving the binary numbers. It keeps on converting.
parseInt(“100110113432”, 2); //155
Alright! We can also do the same tasks with the Octal number system and Hexadecimal number system using the parseInt() function.