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>
After few successes and failures, I came up with this solution:
I liked the idea above of checking the value for not being NaN and use parseFloat, but when I tried it in React infrastructure it didn't work for some reason.
Edit: I found a nicer way without using strings:
I think it's the shortest answer. Maybe even the most efficient, but I could be stand corrected. :)
You could try
Number.isInteger(Number(value))
ifvalue
might be an integer in string form e.gvar value = "23"
and you want this to evaluate totrue
. Avoid tryingNumber.isInteger(parseInt(value))
because this won't always return the correct value. e.g ifvar value = "23abc"
and you use theparseInt
implementation, it would still return true.But if you want strictly integer values then probably
Number.isInteger(value)
should do the trick.Number.isInteger()
is the best way if your browser support it, if not, I think there are so many ways to go:or:
or:
or:
now we can test the results:
So, all of these methods are works, but when the number is very big, parseInt and ^ operator would not works well.
The simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following:
The following solution would also work, although not as elegant as the one above:
Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation.
Or alternatively:
One fairly common incorrect solution is the following:
While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:
You could use this function:
It will return true even if the value is a string containing an integer value.
So, the results will be:
For positive integer values without separators:
Tests 1. if not empty and 2. if value is equal to the result of a replace of a non-digit char in its value.