string: It is the input value, which contains an integer and is to be converted.
radix: It is on the other side specifies which number system is being used in terms of computer, For example, 2-Binary, 8=octal, etc., till 36.
let x = '5helloworld'; console.log(parseInt(x)); let z = '111'; console.log(parseInt(z , 2));
You can see that the parseInt() function has converted a “5helloworld” string into an integer value of 5.
Implementing radix = 2 takes all the input in binary digits like here 111 is converted into 7. By default, the numbers are converted into decimal values.
Now a question might arise, what if we specify radix as 10 only. We can see that by taking another example.
let data = '12'; console.log(parseInt(data, 10));
You can see that we get a decimal value only in the output.
How does the parseInt() function works
The parseInt() function checks for all the numerical values on the left of any alphabet then parses the value into an integer, and that’s how “5helloworld” was converted into 5 as the output.
let y = "-9" let u = "hello" let m = ”9+8” console.log(parseInt(y)); console.log(parseInt(u)); console.log(parseInt(m));
-9 NaN 9
We can see that the sign symbol is also parsed in the output, and if an alphabetical string is input, NaN(Not a Number) is returned.
If you encounter a string with a value having a number on the right side of the alphabet, a big problem can arise as only numbers on the left will be printed.
Also, we used + sign in the third example, but parseInt stopped the reading process and resulted in only showing 9 as the output.
Here, only 6 is shown as the output, and 7 has been ignored.
Converting string to an integer using Number object
The Number() function accepts a value as an argument.
Let’s convert string to int using the Number() function.
let data = "88" console.log(Number(data));
- MIN_VALUE – It gives us the minimum value among a set of numbers.
- MAX_VALUE – It gives us the maximum value among a set of numbers.
- POSITIVE_INFINITY – It gives us the positive infinity when a number overflow occurs.
- NEGATIVE_INFINITY – It gives us the negative infinity when a number overflow occurs.
- NAN – It gives us the Not a Number value when a pure string of alphabets is used instead of integer values.
That’s it for this tutorial.