This article discusses how JavaScript parseInt function works with web browsers.
ParseInt()
This method will be useful in place of converting the string values to integer, if the string represents proper numeric values.
It takes two arguments, one is a string that needs to be converted and another one is radix which is an optional parameter.
Syntax
ParseInt(string,radix)
In String value always the first character will be considered and space will be ignored. If the given string is not numeric, it shows NAN(NOT A NUMBER).
In radix, values can be used between the range of 2 to 36 and based on giving value, number conversion will take place. If 10 is given it's considered as decimal and 2 is binary.
ParseInt("100",10) // returns 100
ParseInt(" 50 ",10) // returns 50
parseInt("111",2) // returns 7
ParseInt("He is 50 years old",10) // returns NAN
If the second argument (radix) is not present, parseInt method will consider default as 10, if radix value starts with 0X, JavaScript considers it as 16(Hex).
ParseInt("567") // returns 567
ParseInt(" 78 ") // returns 78
With the use of parseInt we can perform a different type of number conversion from one format to another format, like hex decimal to decimal and binary to octal. Using toString() method we can achieve this. The example code is given below.
<!DOCTYPE html>
<html>
<head>
<title>Numbers </title>
<h4 style="color:green; bold;">Convert to Numbers</h4>
</head>
<body>
<p style="color:green;">parseInt Method Only with first Argument</p>
<p id="id1"></p>
<p style="color:red;">parseInt Method with radix</p>
<p id="id2"></p>
<p style="color:red;">parseInt Method along with ToString()</p>
<p id="id3"></p>
<script>
document.getElementById("id1").innerHTML = parseInt("50") + " < br > " +
parseInt("32.00") + " < br > " +
parseInt(" 25 ") + " < br > " +
parseInt("He is 50 years old");
document.getElementById("id2").innerHTML = parseInt("50", 8) + " < br > " +
parseInt("1011", 2) + " < br > " +
parseInt("124", 16);
document.getElementById("id3").innerHTML = parseInt(11101100101, 2).toString(16) + " < br > " +
parseInt("101", 2).toString(8) + " < br > " +
parseInt("ABCD", 16).toString(10);
</script>
</body>
</html>
This simple HTML code contains 3 paragraph <p> Tag, these ids are used inside script tag with DOM element of inner HTML tags and performed a parseInt operation. Accordingly output window is attached below.