如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
比较floor()结果与ceil()结果不同。
const isFloat = v => Math.floor(v) !== Math.ceil(v);
> isFloat(1)
= false
> isFloat(1.1)
= true
> isFloat(42)
= false
> isFloat(84.42)
= true
其他回答
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') );
当除以1时检查余数:
function isInt(n) {
return n % 1 === 0;
}
如果你不知道参数是一个数字,你需要两个测试:
function isInt(n){
return Number(n) === n && n % 1 === 0;
}
function isFloat(n){
return Number(n) === n && n % 1 !== 0;
}
2019年更新在这个答案写出来5年后,一个解决方案在ECMA脚本2015中被标准化。这个答案涵盖了这个解决方案。
另一种方法是:
function isFloat(float) {
return /\./.test(float.toString());
}
可能没有其他方法有效,但另一种方法仍然有效。
为什么不这样做:
var isInt = function(n) { return parseInt(n) === n };
任何小数点为零的浮点数(例如1.0、12.00、0.0)都隐式转换为整数,因此无法检查它们是否为浮点数。