JavaScript > Global Reference

Parse float in JavaScript

How to parse a string and returns a floating point number in JavaScript?


By using parseFloat() function we can parse a string and returns a floating point number.

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

<script>
    function myParsing() {
        var a = parseFloat(15) + "</br>";
        var b = parseFloat("15") + "</br>";
        var c = parseFloat("1/2") + "</br>";
        var d = parseFloat("20.5") + "</br>";
        var e = parseFloat("15 20.5") + "</br>";
        var f = parseFloat("   100   ") + "</br>";
        var g = parseFloat("I spent 5 days") + "</br>";

        var r = a + b + c + d + e + f + g;
        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 floating point numbers, for that we are using parseFloat() function.

Onclick of the button "Parse" in the HTML code fires the function myParsing() in the script bloack at the same time parseFloat() function parses a string and returns a floating point number as output.

OUTPUT


 Views: 5737 | Post Order: 184



Write for us






Hosting Recommendations