如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
这个怎么样?
isFloat(num) {
return typeof num === "number" && !Number.isInteger(num);
}
其他回答
它真的不必那么复杂。整数的parseFloat()和parseInt()等价物的数值将相同。因此,您可以这样做:
function isInt(value){
return (parseFloat(value) == parseInt(value)) && !isNaN(value);
}
Then
if (isInt(x)) // do work
这也将允许字符串检查,因此并不严格。如果想要一个强类型的解决方案(也就是,不使用字符串):
function is_int(value){ return !isNaN(parseInt(value * 1) }
const integerCheck = (num) => {
const isInt = (n) => Number(n) === n && n % 1 === 0
const isFloat = (n) => Number(n) === n && n % 1 !== 0
return (isInt(num) || !isFloat(num))
}
console.log( integerCheck('23.3') );
对于整数,我使用这个
function integer_or_null(value) {
if ((undefined === value) || (null === value)) {
return null;
}
if(value % 1 != 0) {
return null;
}
return value;
}
试试这个
let n;
return (n = value % 1) !== 0 && !isNaN(n);
当返回值为false时,表示输入值为浮点数或浮点数字符串,否则输入值为整数numref或整数字符串。
基本上,它需要检查精度值是否不等于零。
另一个是检查正确的字符串编号。
parseInt(yourNumber)=== parseFloat(yourNumber)