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

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

当前回答

function isWholeNumber(num) {
  return num === Math.round(num);
}

其他回答

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

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

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

使用模可以工作:

num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5

请注意,这是基于数字的数值,而不考虑格式。它将包含固定小数点的整数的数值字符串视为整数:

'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5
number = 20.5

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

alert("Integer")

} else {

alert("Decimal")

}

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

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

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

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

parseInt(num) === num

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

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