我在JavaScript中寻找一种简单的方法来检查一个数字是否有小数点(以确定它是否为整数)。例如,

23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
if(number is integer) {...}

当前回答

Number.isInteger(23);  // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false: 

Number.isInteger()是ES6标准的一部分,在IE11中不支持。

NaN, Infinity和非数字参数返回false,而x % 1 != 0返回true。

其他回答

Number.isInteger(23);  // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false: 

Number.isInteger()是ES6标准的一部分,在IE11中不支持。

NaN, Infinity和非数字参数返回false,而x % 1 != 0返回true。

number = 20.5

if (number == Math.floor(number)) {

alert("Integer")

} else {

alert("Decimal")

}

非常酷,也适用于XX.0这样的东西! 它之所以有效,是因为Math.floor()如果有小数,就会将其切掉,因此如果小数与原始数字不同,我们就知道它是小数!并且没有字符串转换:)

function isDecimal(num) {
  return (num !== parseInt(num, 10));
}
function isDecimal(n){
    if(n == "")
        return false;

    var strCheck = "0123456789";
    var i;

    for(i in n){
        if(strCheck.indexOf(n[i]) == -1)
            return false;
    }
    return true;
}

//如何字节化它?

Number.prototype.isInt= function(){
 return this== this>> 0;
}

我总是觉得javascript中的位操作符很糟糕

他们几乎不锻炼。