JavaScript > Global Reference

Parse Integer in JavaScript

How to parse a string into an integer in JavaScript?


By using parseInt() function we can parse a string and returns an integer.

<p>Click the below button to parse an Integer.</p>
<input type="button" onclick="myParsing()" value="Parse">
<p id="myId"></p>

<script>
    function myParsing() {
        var a = parseInt(15) + "</br>";
        var b = parseInt("15") + "</br>";
        var c = parseInt("1.55") + "</br>";
        var d = parseInt("1.2  1.3  1.4") + "</br>";
        var e = parseInt("1 2 3") + "</br>";
        var f = parseInt("it's only RS.10") + "</br>";
        var g = parseInt("I spent 5 days") + "</br>";
        var h = parseInt("015") + "</br>";
        var i = parseInt("15", 15) + "</br>";
        var j = parseInt("15", 10) + "</br>";
        var k = parseInt("1*15") + "</br>";
        var l = parseInt("12", 17) + "</br>"

        var r = a + b + c + d + e + f + g + h + i + j + k + l;
        document.getElementById("myId").innerHTML = r;
    }
</script>

In the above code snippet we have given ID as "myId" to the second <p> element in the HTML code. There is a function myParsing() in the script code which is connected to the onclick of the HTML button. 

We need to parse a strings (Variable values) and returns a integer, for that we are using parseInt() function. Onclick of the button "Parse" in the HTML code fires the function myParsing() in the script code at the same time parseInt() function parses a string and returns integers as output.

OUTPUT

 Views: 731 | Post Order: 185



Write for us