JavaScript Convert String to Float

To convert a string to float in JavaScript, call parseFloat() function and pass the string as argument to it.

parseFloat() function returns a floating point number created from the given string.

The syntax to convert a string str to a float is

parseFloat(str)

Examples

In the following example, we have taken a string in str, and convert this string to float using parseFloat() function.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var str = '3.14';
        var x = parseFloat(str);
        document.getElementById('output').innerHTML = 'Float : ' + x;
    </script>
</body>
</html>

Any spaces around the string will be implicitly trimmed by the parseFloat() function.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var str = '   3.14 ';
        var x = parseFloat(str);
        document.getElementById('output').innerHTML = 'Float : ' + x;
    </script>
</body>
</html>

parseFloat() can also handle scientific notation of floating point number.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var str = '314e-2';
        var x = parseFloat(str);
        document.getElementById('output').innerHTML = 'Float : ' + x;
    </script>
</body>
</html>

If there are any non-digit characters in the given string, those characters would be ignored by parseFloat() function.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var str = '3.14abcd';
        var x = parseFloat(str);
        document.getElementById('output').innerHTML = 'Float : ' + x;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to convert a string into integer using parseFloat() function, with examples.