我在JavaScript中寻找一种简单的方法来检查一个数字是否有小数点(以确定它是否为整数)。例如,
23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
if(number is integer) {...}
我在JavaScript中寻找一种简单的方法来检查一个数字是否有小数点(以确定它是否为整数)。例如,
23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
if(number is integer) {...}
当前回答
可以使用不改变值的位操作(^ 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
其他回答
parseInt(num) === num
当传递一个数字时,parseInt()只是将数字作为int返回:
parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3 // true
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;
}
或者你可以用这个来判断它是不是小数:
string.indexOf(".") == -1;
如果value是字符串(例如from <input),使用下面的语句:
Math.floor(value).toString() !== value
我将. tostring()添加到floor,使其也适用于value == "1 "的情况。(以十进制分隔符或其他字符串结束)。同时数学。floor总是返回一些值,因此. tostring()永远不会失败。
当使用带有十进制步骤的计数器时,检查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)}); }