JavaScript parseFloat() used to convert a string into a floating-point number. The parseFloat() is an inbuilt function in JavaScript, which parses a string and returns a floating-point number.
Syntax
parseFloat(string)
Parameter Values
String Value converted to a floating point number.
Return value
It returns a floating-point Number or if can’t be converted then the function returns NaN i.e, not a number.
Examples of JavaScript parseFloat() method
Let’s see the different example of how to convert string to float number.
Parse Number strings
Simple basic example
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var a = parseFloat("10")
alert(a)
</script>
</body>
</html>
Output:
Different type of string and result
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
a = parseFloat(" 100 ")
document.write('parseFloat(" 100 ") = ' +a +"<br>");
b = parseFloat("2020@abc")
document.write('parseFloat("2020@abc") = '+b +"<br>");
// It returns NaN on Non numeral character
c = parseFloat("xyz@2018")
document.write('parseFloat("xyz@2018") = ' +c +"<br>");
d = parseFloat("3.14")
document.write('parseFloat("3.14") = '+d +"<br>");
// It returns only first Number it encounters
e = parseFloat("22 7 2020")
document.write('parseFloat("22 7 2018") = ' +e +"<br>");
</script>
</body>
</html>
Output
Dealing with float precision in Javascript
Working on a function in JavaScript and take two variables x and y.
Needed to divide two variables and display result on the screen:
x=9; y=110;
x/y;
Getting the result as :
0.08181818181818181
But want that result was shown as:
0.082
Solution
Try this it is rounding to 3 numbers after coma:
(x/y).toFixed(3);
Now your result will be a string. If you need it to be float just do:
parseFloat((x/y).toFixed(3));
Complete example
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
x = 9;
y = 110;
n = parseFloat((x/y).toFixed(3));
alert(n);
</script>
</body>
</html>
How to JavaScript parseFloat comma
Answer: You have to first remove the commas using replace method.
parseFloat(yournumber.replace(/,/g, ''));
Read more: JavaScript replace all Word | space, comma | special characters
Output JavaScript parseFloat empty string
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
x = "";
alert(parseFloat(x));
</script>
</body>
</html>
Note:
- Leading and trailing spaces are allowed.
- Only the first number in the string is returned.
- If the first character can’t be converted to a number, parseFloat() returns NaN.
Do comment if you have any doubts and suggestions on this tutorial.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version