如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
您可以使用Number.isInteger()方法通过对数字进行除法来检查数字是整数还是浮点数,例如:
function isNumberFloatOrInteger(a, b){
if(Number.isInteger(a / b)){
return true;
}
else{ return false };
}
注意:isInteger()与internet explorer不兼容。
其他回答
尝试这些函数来测试一个值是否是一个没有小数部分的数字基元值,并且在可以表示为精确整数的大小范围内。
function isFloat(n) {
return n === +n && n !== (n|0);
}
function isInteger(n) {
return n === +n && n === (n|0);
}
基于我在这里看到的所有内容,我创建了自己的一组函数来测试我所需要的:
function NumberValidator() {
this.isFloat = function (n) {
return typeof(n)==="number" && n === +n && Math.round(n) !== n;
};
this.isInteger = function (n) {
return typeof(n)==="number" && n === +n && Math.round(n) === n;
};
this.isFloatOrInteger = function (n) {
return this.isFloat(n) || this.isInteger(n);
};
this.isNonZeroFloatOrInteger = function (n) {
return this.isFloatOrInteger(n) && n > 0;
};
this.isNonZeroInteger = function (n) {
return this.isInteger(n) && n > 0;
};
}
然而,shime的解决方案更短,检查更少,因此可能是更好的解决方案。
浮动验证条件:
if (lnk.value == +lnk.value && lnk.value != (lnk.value | 0))
整数验证条件:
if (lnk.value == +lnk.value && lnk.value == (lnk.value | 0))
希望这可能会有所帮助。
function isInteger(n) {
return ((typeof n==='number')&&(n%1===0));
}
function isFloat(n) {
return ((typeof n==='number')&&(n%1!==0));
}
function isNumber(n) {
return (typeof n==='number');
}
您可以使用Number.isInteger()方法通过对数字进行除法来检查数字是整数还是浮点数,例如:
function isNumberFloatOrInteger(a, b){
if(Number.isInteger(a / b)){
return true;
}
else{ return false };
}
注意:isInteger()与internet explorer不兼容。