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