Home > Article > Web Front-end > How to Check if a Variable is an Integer in JavaScript?
Checking if a Variable is an Integer in JavaScript
When working with JavaScript, it's common to need to check the type of a variable. If you need to verify whether a particular variable is an integer, follow these steps:
Using a Function
function isInt(value) { return !isNaN(value) && parseInt(Number(value)) == value && !isNaN(parseInt(value, 10)); }
isInt(22); // returns true isInt("22.5"); // returns false
Using Bitwise Operations
(x | 0) === x
Where x is the variable you want to check.
For example:
42 | 0 === 42 // returns true 42.1 | 0 === 42 // returns false
Note:
var x; if (isNaN(value)) { return false; } x = parseFloat(value); return (x | 0) === x;
return isNaN(value) ? !1 : (x = parseFloat(value), (0 | x) === x);
The above is the detailed content of How to Check if a Variable is an Integer in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!