Skip to content

JavaScript string to float | Example code

  • by

Use JavaScript parseFloat() method to convert a string into float. This method parses a value as a string and returns the first number.

Note: If the first character cannot be converted, NaN is returned.

JavaScript string to float

Simple example code.

 <!DOCTYPE html>
 <html>
 <body>

  <script>
    console.log(parseFloat(10));
    console.log(("10"));
    console.log(("10.00"));
    console.log(("100 200 300"));
    console.log(("Age 40"));
  </script>

</body>
</html> 

Output:

JavaScript string to float

How to convert a string into a float in JavaScript?

Answer: Get the numbers after the comma.

var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])

If they’re meant to be a single value (like in French, where one-half is written 0,5)

var value = parseFloat("554,20".replace(",", "."));

Do comment if you have any doubts or suggestions on this JS string conversion.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *