我正在寻找一种在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
}
parseInt(num) === num
parseInt()
会将其返回为整数: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;
}
如果值是字符串(例如来自<input
),请使用以下内容:
Math.floor(value).toString() !== value
我在 floor 后面添加了 .toString(),以使其在 value == "1." (以小数分隔符或其他字符串结尾) 的情况下也能正常工作。另外,Math.floor 总是返回一个值,因此 .toString() 永远不会失败。
if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}
^ 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
这是我从David Herman的《Effective JavaScript》中得到灵感后编写的guard库的摘录:
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
function isWholeNumber(num) {
return num === Math.round(num);
}
const isRound = number => number.toFixed(9).endsWith('000000000');
for (let counter = 0; counter < 2; counter += 0.1) {
console.log({ counter, modulo: counter % 1, formatted: counter.toFixed(9), isRound: isRound(counter) });
}
function isDecimal(num) {
return (num !== parseInt(num, 10));
}
parseInt(3.0) === 3.0 // true
的函数失败。 - zipzit