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

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

当前回答

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

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

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

其他回答

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

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

string.indexOf(".") == -1;

你可以用这个:

bool IsInteger() {
    if (num.indexOf(".") != -1) // a decimal
    {
        return Math.ceil(num) == Math.floor(num); // passes for 1.0 as integer if thats the intent.
    }
    return Number.isSafeInteger(num);
}

检查该数字是整数还是十进制。

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

当使用带有十进制步骤的计数器时,检查number是否为整数实际上会失败,如下所示。因此,用小数点后9位(可能更多)来格式化数字可能是最安全的(尽管速度较慢),如果它以9个零结尾,那么它就是一个整数。

const isRound = number => number. tofixed (9).endsWith('000000000'); For (let counter = 0;Counter < 2;计数器+= 0.1){ console.log({counter, modulo: counter % 1,格式化:counter. tofixed (9), isRound: isRound(counter)}); }