How to check if a variable is an integer in JavaSc

2019-01-01 02:47发布

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>

标签: javascript
30条回答
像晚风撩人
2楼-- · 2019-01-01 03:19

You could check if the number has a remainder:

var data = 22;

if(data % 1 === 0){
   // yes it's an integer.
}

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:

var data = 22;

if(typeof data === 'number'){
     // yes it is numeric

    if(data % 1 === 0){
       // yes it's an integer.
    }
}
查看更多
刘海飞了
3楼-- · 2019-01-01 03:19

Check if the variable is equal to that same variable rounded to an integer, like this:

if(Math.round(data) != data) {
    alert("Variable is not an integer!");
}
查看更多
时光乱了年华
4楼-- · 2019-01-01 03:19

I had to check if a variable (string or number) is an integer and I used this condition:

function isInt(a){
    return !isNaN(a) && parseInt(a) == parseFloat(a);
}

http://jsfiddle.net/e267369d/1/

Some of the other answers have a similar solution (rely on parseFloat combined with isNaN), 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:

function isInt(a){
    return !isNaN(a) && parseInt(a) == parseFloat(a) && (typeof a != 'string' || (a.indexOf('.') == -1 && a.indexOf(',') == -1));
}

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.

查看更多
大哥的爱人
5楼-- · 2019-01-01 03:20

You can use regexp for this:

function isInteger(n) {
    return (typeof n == 'number' && /^-?\d+$/.test(n+''));
}
查看更多
时光乱了年华
6楼-- · 2019-01-01 03:21

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.

查看更多
有味是清欢
7楼-- · 2019-01-01 03:23

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

Number.isInteger = Number.isInteger || function(value) {
    return typeof value === "number" && 
           isFinite(value) && 
           Math.floor(value) === value;
};
查看更多
登录 后发表回答