In JavaScript, the easiest way to check if a number is a whole number is by using the Number.isInteger() method.
console.log(Number.isInteger(2.0))
console.log(Number.isInteger(2.1))
#Output:
True
False
In JavaScript, when working with numbers, it can be useful to be able to find out if a number is a whole number.
We can easily check if a number is a whole number with the help of the Number.isInteger() method.
The isInteger() method returns a boolean indicating if the number is an integer or not.
JavaScript Check If Number is a Whole Number With a Click
Below we will provide code to let the user input a number, and then use the isInteger() method to check if the number is a whole number. Here is our simple HTML setup:
<p>Type a number to see if it is a whole number:</p>
<input id="userVal" type="text" value="" onkeyup="checkNum(event)">
<input id="submitNum" type="submit" value="Submit" onclick="checkNum('click')">
<div id="results"></div>
Below is the JavaScript code which take the user input using the onkeyup event or the onclick event along with the value property and use the Number.isInteger() method on that user input and update the results below using the textContent property.
Here is the JavaScript code:
function checkNum(e) {
//If we clicked or pressed enter, run the following code
if( e == 'click' || e.keyCode == 13 ){
var userNum = document.getElementById("userVal").value;
//Check if number is whole
var isWhole = Number.isInteger(Number(userNum));
//Show the result to the user to the user
document.getElementById("results").textContent = isWhole;
}
};
The final code and output for this example are below:
Code Output:
Type a number to see if it is a whole number:
Full Code:
<p>Type a number to see if it is a whole number:</p>
<input id="userVal" type="text" value="" onkeyup="checkNum(event)">
<input id="submitNum" type="submit" value="Submit" onclick="checkNum('click')">
<div id="results"></div>
<script>
function checkNum(e) {
if( e == 'click' || e.keyCode == 13 ){
var userNum = document.getElementById("userVal").value;
var isWhole = Number.isInteger(Number(userNum));
document.getElementById("results").textContent = isWhole;
}
};
</script>
Hopefully this article has been useful in helping you understand how to use JavaScript to check if whole number.
Leave a Reply