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

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

当前回答

function isDecimal(num) {
  return (num !== parseInt(num, 10));
}

其他回答

可以使用不改变值的位操作(^ 0或~~)来丢弃小数部分,小数部分可用于舍入。四舍五入后,将其与原始值进行比较:

function isDecimal(num) {
  return (num ^ 0) !== num;
}

console.log( isDecimal(1) ); // false
console.log( isDecimal(1.5) ); // true
console.log( isDecimal(-0.5) ); // true

以下是我的守卫库的摘录(灵感来自David Herman的Effective JavaScript):

var guard = {

    guard: function(x) {
        if (!this.test(x)) {
            throw new TypeError("expected " + this);
        }
    }

    // ...
};

// ...

var number = Object.create(guard);
number.test = function(x) {
    return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
    return "number";
};


var uint32 = Object.create(guard);
uint32.test = function(x) {
    return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
    return "uint32";
};


var decimal = Object.create(guard);
decimal.test = function(x) {
    return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
    return "decimal";
};


uint32.guard(1234);     // fine
uint32.guard(123.4);    // TypeError: expected uint32

decimal.guard(1234);    // TypeError: expected decimal
decimal.guard(123.4);   // fine
number = 20.5

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

alert("Integer")

} else {

alert("Decimal")

}

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

或者你可以用这个来判断它是不是小数:

string.indexOf(".") == -1;
function isWholeNumber(num) {
  return num === Math.round(num);
}