. Advertisement .
..3..
. Advertisement .
..4..
The built-in Number type comes with a method to help you check if a Value is an Integer in JavaScript. Let’s learn about it with the explanation and examples below.
What can we do to check if a Value is an Integer in JavaScript?
Solution 1: Number.isInteger()
Number
Number is a primitive wrapper object representing and manipulating numbers like 20 or -5.6.
Click here to know more about Number.
Syntax:
Number.isInteger(Value)
Parameters
Value is the value that needs to be checked.
Return value
true if the given value is an integer. Otherwise false.
Let’s see an example below.
<html>
<head>
<title>Check if Value is an Integer in JavaScript.</title>
</head>
<body>
<h2>Check if Value is an Integer in JavaScript using <i> isInteger() </i> method.</h2>
<h4>Output for value 9.</h4>
<div id = "result_1"></div>
<h4>Output for -Infinity.</h4>
<div id = "result_2"></div>
<h4>Output for 3.45.</h4>
<div id = "result_3"></div>
<h4>Output for "Tutopal".</h4>
<div id = "result_4"></div>
<h4>Output for true.</h4>
<div id = "result_5"></div>
<h4>Output for -100.</h4>
<div id = "result_6"></div>
<script>
let result_1 = document.getElementById("result_1");
let result_2 = document.getElementById("result_2");
let result_3 = document.getElementById("result_3");
let result_4 = document.getElementById("result_4");
let result_5 = document.getElementById("result_5");
let result_6 = document.getElementById("result_6");
let number = 9;
result_1.innerHTML = Number.isInteger(number);
let num = -Infinity;
result_2.innerHTML = Number.isInteger(num);
let fl = 3.45;
result_3.innerHTML = Number.isInteger(fl);
let str = "Tutopal"
result_4.innerHTML = Number.isInteger(str);
let bool = true;
result_5.innerHTML = Number.isInteger(bool);
number = -100;
result_6.innerHTML = Number.isInteger(number);
</script>
</body>
</html>
Output:
Check if Value is an Integer in JavaScript using isInteger() method.
Output for value 9.
true
Output for -Infinity.
false
Output for 3.45.
false
Output for “Tutopal”.
false
Output for true.
false
Output for -100.
true
Solution 2: Math.round()
If a number is an Integer, it will remain the same after being rounded.
Syntax:
Math.round(Value)
Parameters
Value: Required a number.
Return value
The number is rounded to the nearest integer.
Look at the example below.
function isIntegerValue(value) {
return Math.round(value) === value;
}
console.log(isIntegerValue(100));
console.log(isIntegerValue(5.5));
Output:
true
false
Note that the round() method handles non-numbers correctly because Math.round() always returns numbers.
Summary
To check if a Value is an Integer in JavaScript, you can use the isInteger() method of Number objects or the round() method of Math objects. These are some solutions that can help you. We hope this tutorial is helpful to you. Thanks!
Read more
Leave a comment