We can convert a string to float in JavaScript by using the JavaScript parseFloat() method.

var num = parseFloat("20.12345");

The above code would return the number 20.12345.


The parseFloat() JavaScript method will parse the value given to it as a string and then return the first Float in the string. If no number is found at the start, NaN will be returned.

Some other examples of the parseFloat() method are below:

var num1 = parseFloat("$11");
var num2 = parseFloat("30 40 50");
var num3 = parseFloat("The first number is 2 followed by 3");
var num4 = parseFloat("10.10 is the first number");
var num5 = parseFloat("-10.59 50.50");

console.log(num1);
console.log(num2);
console.log(num3);
console.log(num4);
console.log(num5);

#Output
NaN
30
NaN
10.1
-10.59

Note the parseFloat() JavaScript method is similar to the parseInt() method, the main difference being that parseInt() will only return the Integer, while parseFloat() will return decimal values as well.

Convert String to Float using JavaScript

Below we will provide code to let the user input a string, and then use the parseFloat() method to return the first number. Here is our simple HTML setup:

Type something you want to use the parseFloat() method on below:


Convert to Float

Below is the JavaScript code which takes the user input using an onclick event, and uses the parseFloat() method on that user input. We update the results below using the textContent property.

function convertStringToFloat(){
  document.getElementById("results").textContent = parseFloat(document.getElementById("userVal").value);
};

The final code and output for this example is below:

Code Output:

Type something you want to use the parseFloat() method on below:

Convert to Float

Full Code:

Type something you want to use the parseFloat() method on below:


Convert to Float



Hopefully this article has been useful in helping you understand how to convert a string to float in JavaScript.

Read more here.

Categorized in:

JavaScript,

Last Update: May 3, 2024