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

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

当前回答

Number.isInteger()可能是最简洁的。如果是整数则返回true,如果不是则返回false。

其他回答

简单,但有效!

Math.floor(number) === number;
parseInt(num) === num

当传递一个数字时,parseInt()只是将数字作为int返回:

parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3     // true

如果value是字符串(例如from <input),使用下面的语句:

Math.floor(value).toString() !== value

我将. tostring()添加到floor,使其也适用于value == "1 "的情况。(以十进制分隔符或其他字符串结束)。同时数学。floor总是返回一些值,因此. tostring()永远不会失败。

可以使用不改变值的位操作(^ 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

//如何字节化它?

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

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

他们几乎不锻炼。