By using parseFloat() Method
In this method, we will use the parseFloat() method which is an inbuilt function in JavaScript that is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then 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) {
// Using parseFloat() method
let floatValue = parseFloat(a);
// Return float value
return floatValue;
}
//Driver code
let n = "245.165";
// Call function
n = convert_to_float(n);
// Print result
console.log("Converted value = " + n +
" Type of " + n + " = " + typeof n);
n = "-915.55";
// Call function
n = convert_to_float(n);
// Print result
console.log("Converted value = " + n +
" Type of " + n + " = " + typeof n);
Output
Converted value = 245.165 Type of 245.165 = number Converted value = -915.55 Type of -915.55 = number
Special Case: In French, float numbers are written by the use of a comma (, ) as a separator instead of a dot(.) as a separator.
Example:
The value 245.67 in French is written as 245, 67
To convert a French string into a float in JavaScript we will first use replace() method to replace every (, ) with (.) then follow any of the above-described methods.
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) {
// Using parseFloat() method
// and using replace() method
// to replace ', ' with '.'
let floatValue = parseFloat(a.replace(/, /, "."));
// Return float value
return floatValue;
}
//Driver code
let n = "245, 165";
// Call function
n = convert_to_float(n);
// Print result
console.log("Converted value = " + n +
" Type of " + n + " = " + typeof n);
n = "-915, 55";
// Call function
n = convert_to_float(n);
// Print result
console.log("Converted value = " + n +
" Type of " + n + " = " + typeof n);
Output
Converted value = 245.165 Type of 245.165 = number Converted value = -915.55 Type of -915.55 = 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: