我在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 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;
}
其他回答
var re=/^-?[0-9]+$/;
var num=10;
re.test(num);
以下是我的守卫库的摘录(灵感来自David Herman的Effective JavaScript):
var guard = {
guard: function(x) {
if (!this.test(x)) {
throw new TypeError("expected " + this);
}
}
// ...
};
// ...
var number = Object.create(guard);
number.test = function(x) {
return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
return "number";
};
var uint32 = Object.create(guard);
uint32.test = function(x) {
return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
return "uint32";
};
var decimal = Object.create(guard);
decimal.test = function(x) {
return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
return "decimal";
};
uint32.guard(1234); // fine
uint32.guard(123.4); // TypeError: expected uint32
decimal.guard(1234); // TypeError: expected decimal
decimal.guard(123.4); // fine
Number.isInteger(23); // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false:
Number.isInteger()是ES6标准的一部分,在IE11中不支持。
NaN, Infinity和非数字参数返回false,而x % 1 != 0返回true。
//如何字节化它?
Number.prototype.isInt= function(){
return this== this>> 0;
}
我总是觉得javascript中的位操作符很糟糕
他们几乎不锻炼。
function isWholeNumber(num) {
return num === Math.round(num);
}