我在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) {...}
当前回答
将数字字符串转换为数组,以小数点分割。然后,如果数组只有一个值,这意味着字符串中没有小数。
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
}
其他回答
使用模可以工作:
num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5
请注意,这是基于数字的数值,而不考虑格式。它将包含固定小数点的整数的数值字符串视为整数:
'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5
parseInt(num) === num
当传递一个数字时,parseInt()只是将数字作为int返回:
parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3 // true
可以使用不改变值的位操作(^ 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
函数检查数字是十进制或整数
function IsDecimalExist(p_decimalNumber) {
var l_boolIsExist = true;
if (p_decimalNumber % 1 == 0)
l_boolIsExist = false;
return l_boolIsExist;
}
以下是我的守卫库的摘录(灵感来自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