我在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()永远不会失败。

其他回答

Number.isSafeInteger(value);

在JavaScript中,isSafeInteger()是一个Number方法,用于返回一个布尔值,指示一个值是否为安全整数。这意味着它是一个整数值,可以精确地表示为IEEE-754双精度数,而不需要舍入。

你可以用这个:

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

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

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

他们几乎不锻炼。

将数字字符串转换为数组,以小数点分割。然后,如果数组只有一个值,这意味着字符串中没有小数。

if(!number.split(".")[1]){
    //do stuff
}

这样你也可以知道整数和小数到底是什么。一个更高级的例子是。

number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1]; 

if(!dece){
    //do stuff
}