JavaScript - parseFloat() method

revision:


Category : number

The Number.parseFloat() static method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns NaN.

Syntax :

        Number.parseFloat(string)
    

Parameters:

string : required. The value to parse, coerced to a string. Leading whitespace in this argument is ignored.

: optional. .

Examples:

        function circumference(r) {
            if (Number.isNaN(Number.parseFloat(r))) {
              return 0;
            }
            return parseFloat(r) * 2.0 * Math.PI ;
        }
        console.log(circumference('4.567abcdefgh'));
          // Expected output: 28.695307297889173
        console.log(circumference('abcdefgh'));
          // Expected output: 0
        Number.parseFloat === parseFloat; // true
    

Practical examples

example: parse a string and return the first number.

code:
                    <div>
                        <p id="parse-1"></p>
                    </div>
                    <script>
                        document.getElementById("parse-1").innerHTML = "parse a string and returns the first number: <br>" +
                            Number.parseFloat(10) + "<br>" +
                            Number.parseFloat("10") + "<br>" +
                            Number.parseFloat("10.33") + "<br>" +
                            Number.parseFloat("34 45 66") + "<br>" +
                            Number.parseFloat("He was 40");
                    </script>
                

example: parse a string and reurn the first number.

code:
                    <div>
                        <p id="parse-2"></p>
                    </div>
                    <script>
                        document.getElementById("parse-2").innerHTML = "parse a string and returns the first number: <br>" +
                            Number.parseFloat("40.00") + "<br>" +
                            Number.parseFloat("   40   ") + "<br>" +
                            Number.parseFloat("40 years") + "<br>" +
                            Number.parseFloat("40H") + "<br>" +
                            Number.parseFloat("H40");
                    </script>