The parseFloat JavaScript method will parse the value given to it as a string and then return the first number in the string. This is done using the parseFloat() method.
var num = parseFloat("20");
The above code would return the number 20.
Some other examples of the parseFloat() method are below:
var num1 = parseFloat(1);
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 50");
Which would result in the following:
1
30
NaN
10.1
-10
Note that the parseInt() method is similar to the parseFloat() method, the main difference being that parseInt will only return the Integer, while parseFloat will return decimal values as well.
parseFloat() in action using jQuery
Below we will provide code to let the user input a number or string, and then use the parseFloat() method to return the first number. Here is our simple HTML setup:
Type a number or string you want to use the parseFloat() method on below:
Below is the JavaScript and jQuery code which take the user input using the jQuery click() or on() keypress methods, and use the parseFloat() method on that user input and update the results below using the jQuery text() method.
$('#userVal').on('keypress',function(e) {
if(e.which == 13) {
$("#results").text(parseFloat($("#userVal").val()));
}
});
$("#submitNum").click(function(){
$("#results").text(parseFloat($("#userVal").val()));
});
The final code and output for this example is below:
Code Output:
Type a number or string you want to use the parseFloat() method on below:
Full Code:
Type a number or string you want to use the parseFloat() method on below:
<script>
$('#userVal').on('keypress',function(e) {
if(e.which == 13) {
$("#results").text(parseFloat($("#userVal").val()));
}
});
$("#submitNum").click(function(){
$("#results").text(parseFloat($("#userVal").val()));
});
</script>
Hopefully this article has been useful in helping you understand the parseFloat JavaScript method.