We can use JavaScript to convert a float to an integer by using the JavaScript parseInt() method.
var num = parseInt(20.12345);
The above code would return the number 20.
The parseInt() JavaScript method will parse the value given varaible to it and then return the Integer value. If no integer is found at the start, NaN will be returned.
Some other examples of the parseInt() method are below:
var num1 = parseInt(40.7245);
var num2 = parseInt(.273983678);
var num3 = parseInt(-1.28980);
var num4 = parseInt(-.93898);
var num5 = parseInt("$11.345");
console.log(num1);
console.log(num2);
console.log(num3);
console.log(num4);
console.log(num5);
#Output
40
0
-1
0
NaN
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.
Convert Float to Integer using JavaScript
Below we will provide code to let the user input a float, and then use the parseInt() method to return the Integer. Here is our simple HTML setup:
<p>Type a number you want to use the parseInt() method on below:</p>
<input id="userVal" type="number" value="">
<div id="click-me" onclick="convertFloatToInt()">Convert to Integer</div>
<div id="results"></div>
Below is the JavaScript code which takes the user input using an onclick event, and uses the parseInt() method on that user input. We update the results below using the textContent property.
function convertFloatToInt(){
document.getElementById("results").textContent = parseInt(Number(document.getElementById("userVal").value));
};
The final code and output for this example is below:
Code Output:
Type a number you want to use the parseInt() method on below:
Full Code:
<p>Type a number you want to use the parseInt() method on below:</p>
<input id="userVal" type="number" value="">
<div id="click-me" onclick="convertFloatToInt()">Convert to Integer</div>
<div id="results"></div>
<script>
function convertFloatToInt(){
document.getElementById("results").textContent = parseInt(Number(document.getElementById("userVal").value));
};
</script>
Hopefully this article has been useful in helping you understand how to use JavaScript to convert a float to int.
Leave a Reply