我在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) {...}
当前回答
你可以把它乘以10,然后用10做一个“模数”运算/除法,然后检查这两个运算的结果是否为零。这两个操作的结果将给出小数点后的第一个数字。 如果result等于0,则该数为整数。
if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}
其他回答
function isDecimal(num) {
return (num !== parseInt(num, 10));
}
简单,但有效!
Math.floor(number) === number;
var re=/^-?[0-9]+$/;
var num=10;
re.test(num);
//如何字节化它?
Number.prototype.isInt= function(){
return this== this>> 0;
}
我总是觉得javascript中的位操作符很糟糕
他们几乎不锻炼。
parseInt(num) === num
当传递一个数字时,parseInt()只是将数字作为int返回:
parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3 // true