By using the eval() function
In this method, we will use the eval() method which is an inbuilt function in JavaScript that is used to evaluate the string return result. If the string contains a number then it converts it from string to number and then returns it and if contains other than the number it returns NaN i.e, not a number. Example: Below program demonstrates the above approach
// Javascript script
// to convert string
// to float value
// Function to convert
// string to float value
function convert_to_float(a) {
// Type conversion
// of string to float
let floatValue = eval(a);
// Return float value
return floatValue;
}
//Driver code
let n = "55.225";
// Call function
n = convert_to_float(n);
// Print result
console.log("Converted value = " + n +
" Type of " + n + " = " + typeof n);
n = "-33.565";
// Call function
n = convert_to_float(n);
// Print result
console.log("Converted value = " + n +
" Type of " + n + " = " + typeof n);
Output
Converted value = 55.225 Type of 55.225 = number Converted value = -33.565 Type of -33.565 = number
How to convert string into float in JavaScript?
In this article, we will convert a string into a float in Javascript. We can convert a string into a float in JavaScript by using some methods which are described below: