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

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

当前回答

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;
}

其他回答

你可以用这个:

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);
}

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

number = 20.5

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

alert("Integer")

} else {

alert("Decimal")

}

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

使用模可以工作:

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

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

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