In JavaScript, one way to check if a variable is of type integer, Number.isInteger()
can be used:
Number.isInteger(22); // true
Number.isInteger(22.2); // false
Number.isInteger('22'); // false
Nevertheless, this solution has the disadvantage, that a string with integer value like '22'
will result in false
. But there are different solutions for this:
Use parseInt
You can use the parseInt
function to parse a string and convert it into an integer. If the string signifies an integer parseInt
will provide that value. Otherwise it will yield NaN
(Not a Number). You can verify if the outcome is numeric or not to ascertain if the string signifies an integer. Here’s how you can accomplish this…
function isInteger(value) {
return +value === parseInt(value);
}
isInteger(22); // true
isInteger(22.2); // false
isInteger('22'); // true
This will result in true
for integer 22
as well as an integer “string” '22'
.
Use Number()
Similar to the parseInt
solution, you can also use Number()
for this. Number
values represent floating-point numbers like 37
or -9.25
(see its documentation). So to check for an integer value, you need to use Number.isInteger(). Otherwise, the result is also true for decimal values.
function isInteger(value) {
return +value === Number(value) && Number.isInteger(Number(value));
}
isInteger(22); // true
isInteger(22.2); // false
isInteger('22'); // true
Use regular expression
function isInteger(value) {
// Use regular expression to check if the value consists only of digits
return /^\d+$/.test(value);
}
isInteger(22); // true
isInteger(22.2); // false
isInteger('22'); // true
This function isInteger
verifies whether the string contains numbers (0 9) by utilizing a pattern matching technique. If it indeed contains digits it will return true
signifying that the string denotes an integer value; otherwise it will return false
.
Leave a Reply