如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
基于我在这里看到的所有内容,我创建了自己的一组函数来测试我所需要的:
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的解决方案更短,检查更少,因此可能是更好的解决方案。
其他回答
以下是我对整数的用法:
Math.ceil(parseFloat(val)) === val
很短,很好:)一直工作。如果我没弄错的话,这就是大卫·弗拉纳根的建议。
尝试这些函数来测试一个值是否是一个没有小数部分的数字基元值,并且在可以表示为精确整数的大小范围内。
function isFloat(n) {
return n === +n && n !== (n|0);
}
function isInteger(n) {
return n === +n && n === (n|0);
}
这可能不如%answer的性能好,它可以防止您首先转换为字符串,但我还没有看到任何人发布它,所以这里有另一个选项应该可以正常工作:
function isInteger(num) {
return num.toString().indexOf('.') === -1;
}
var isInt = function (n) { return n === (n | 0); };
还没有这样的案例。
有一个名为Number.isInteger()的方法,它目前在除IE.MDN之外的所有浏览器中都实现了。MDN还为其他浏览器提供了一个polyfill:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value;
};
但是,对于大多数使用情况,最好使用Number.isSafeInteger,它还可以检查值是否太高/太低,以至于任何小数点都会丢失。MDN也为此提供了一种聚菲。(您还需要上面的isInteger民意测验。)
if (!Number.MAX_SAFE_INTEGER) {
Number.MAX_SAFE_INTEGER = 9007199254740991; // Math.pow(2, 53) - 1;
}
Number.isSafeInteger = Number.isSafeInteger || function (value) {
return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
};