如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
可以使用简单的正则表达式:
function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);
}
或者,您也可以根据需要使用以下功能。它们由PHPJS项目开发。
is_int()=>检查变量类型是否为整数,其内容是否为整数
is_float()=>检查变量类型是否为float,其内容是否为floate
ctype_digit()=>检查变量类型是否为字符串,以及其内容是否只有小数位数
更新1
现在它也检查负数,感谢@ChrisBartley的评论!
其他回答
这可能不如%answer的性能好,它可以防止您首先转换为字符串,但我还没有看到任何人发布它,所以这里有另一个选项应该可以正常工作:
function isInteger(num) {
return num.toString().indexOf('.') === -1;
}
function isInteger(x) { return typeof x === "number" && isFinite(x) && Math.floor(x) === x; }
function isFloat(x) { return !!(x % 1); }
// give it a spin
isInteger(1.0); // true
isFloat(1.0); // false
isFloat(1.2); // true
isInteger(1.2); // false
isFloat(1); // false
isInteger(1); // true
isFloat(2e+2); // false
isInteger(2e+2); // true
isFloat('1'); // false
isInteger('1'); // false
isFloat(NaN); // false
isInteger(NaN); // false
isFloat(null); // false
isInteger(null); // false
isFloat(undefined); // false
isInteger(undefined); // false
我参加晚会迟到了,但这是我的版本
isInteger: obj => Number.isInteger(!isNaN(obj % 1) && obj % 1 !== 0 ? obj : parseInt(obj)),
任何小数点为零的浮点数(例如1.0、12.00、0.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的解决方案更短,检查更少,因此可能是更好的解决方案。