How do I check if a variable is an integer in JavaScript, and throw an alert if it isn't? I tried this, but it doesn't work:
<html>
<head>
<script type="text/javascript">
var data = 22;
alert(NaN(data));
</script>
</head>
</html>
You could check if the number has a remainder:
Mind you, if your input could also be text and you want to check first it is not, then you can check the type first:
Check if the variable is equal to that same variable rounded to an integer, like this:
I had to check if a variable (string or number) is an integer and I used this condition:
http://jsfiddle.net/e267369d/1/
Some of the other answers have a similar solution (rely on
parseFloat
combined withisNaN
), but mine should be more straight forward and self explaining.Edit: I found out that my method fails for strings containing comma (like "1,2") and I also realized that in my particular case I want the function to fail if a string is not a valid integer (should fail on any float, even 1.0). So here is my function Mk II:
http://jsfiddle.net/e267369d/3/
Of course in case you actually need the function to accept integer floats (1.0 stuff), you can always remove the dot condition
a.indexOf('.') == -1
.You can use regexp for this:
ECMA-262 6.0 (ES6) standard include Number.isInteger function.
In order to add support for old browser I highly recommend using strong and community supported solution from:
https://github.com/paulmillr/es6-shim
which is pure ES6 JS polyfills library.
Note that this lib require es5-shim, just follow README.md.
Number.isInteger()
seems to be the way to go.MDN has also provided the following polyfill for browsers not supporting
Number.isInteger()
, mainly all versions of IE.Link to MDN page