Wednesday 29 August 2018

JavaScript: parseFloat: Convert string to float

parseFloat(string)
parseFloat takes a string and return a float value.

Ex:
var a = parseFloat("123.45"); // Return 123.45
var b = parseFloat("0.987654"); // Return 0.987654

parseFloat converts the character by character, if it is unable to convert any character it ignores it and all succeeding characters and returns the float value parsed up to that point.

var c = parseFloat("123.45awq34"); // Return 123.45

If the first character cannot be converted to a number, parseFloat returns NaN.

var d = parseFloat("a1234"); // Return NaN

parseFloat.html
<!DOCTYPE html>

<html>

<head>
    <title>parseFloat</title>
</head>

<body>
    <script type="text/javascript">
        var a = parseFloat("123.45"); // Return 123.45
        var b = parseFloat("0.987654"); // Return 0.987654
        var c = parseFloat("123.45awq34"); // Return 123.45
        var d = parseFloat("a1234"); // Return NaN

        document.write("a = " + a + "<br />");
        document.write("b = " + b + "<br />");
        document.write("c = " + c + "<br />");
        document.write("d = " + d + "<br />");
    </script>
</body>

</html>



Previous                                                 Next                                                 Home

No comments:

Post a Comment