我在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) {...}
当前回答
function isWholeNumber(num) {
return num === Math.round(num);
}
其他回答
Number.isInteger(23); // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false:
Number.isInteger()是ES6标准的一部分,在IE11中不支持。
NaN, Infinity和非数字参数返回false,而x % 1 != 0返回true。
var re=/^-?[0-9]+$/;
var num=10;
re.test(num);
或者你可以用这个来判断它是不是小数:
string.indexOf(".") == -1;
将数字字符串转换为数组,以小数点分割。然后,如果数组只有一个值,这意味着字符串中没有小数。
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
}
//如何字节化它?
Number.prototype.isInt= function(){
return this== this>> 0;
}
我总是觉得javascript中的位操作符很糟糕
他们几乎不锻炼。