JavaScript parseFloat() function : The parseFloat() function is used to get the floating point number from a passed string. It first parse the string and then return the number as a decimal number.
Syntax of parseFloat() function :
parseFloat(param)
param : required parameter, this could be string or any object need to parse and return as floating number.
The parseFloat() always return a number, if it has decimal number then it returns number as a decimal number. If we pass string starting with number then it will remove the string and only return the first number found. If it does not found number then it just returns NaN.
Example of parseFloat() function : Here is the sample example which shows how to parse a string to a float or decimal number.
<!DOCTYPE html>
<html>
<body>
<p>To parse strings to float number, click the button.</p>
<button onclick="myFunction()">parse</button>
<p id="container"></p>
<script>
function myFunction() {
var var1 = parseFloat("21") + "<br>";
var var2 = parseFloat("5.00") + "<br>";
var var3 = parseFloat("34.03") + "<br>";
var var4 = parseFloat("16 12 21") + "<br>";
var var5 = parseFloat(" 44 ") + "<br>";
var var6 = parseFloat("15 cars") + "<br>";
var var7 = parseFloat("count 20") + "<br>";
var num = var1 + var2 + var3 + var4 + var5 + var6 + var7;
document.getElementById("container").innerHTML = num;
}
</script>
</body>
</html>
Output :
21
5
34.03
16
44
15
NaN
0 Comment(s)