如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
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 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');
}
它真的不必那么复杂。整数的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) }
简单整数测试:
if( n === parseInt(n) ) ...
有意义:如果JavaScript可以将某个东西转换为整数,并且通过转换它变成完全相同的东西,那么操作数就是整数。
控制台测试用例:
x = 1; x===parseInt(x); // true
x = "1"; x===parseInt(x); // false
x = 1.1; x===parseInt(x); // false, obviously
// BUT!
x = 1.0; x===parseInt(x); // true, because 1.0 is NOT a float!
这让很多人困惑。每当某个值为0时,它就不再是浮球了。这是一个整数。或者你可以把它称为“一个数字的东西”,因为没有像当时的C那样严格的区分。
所以基本上,你所能做的就是检查整数,接受1.000是整数的事实。
有趣的侧记
有人评论说数字巨大。巨大的数字意味着这种方法没有问题;每当parseInt无法处理该数字(因为它太大)时,它将返回实际值以外的其他值,因此测试将返回FALSE。看:
var a = 99999999999999999999;
var b = 999999999999999999999; // just one more 9 will kill the show!
var aIsInteger = ( a===parseInt(a) )?"a is ok":"a fails";
var bIsInteger = ( b===parseInt(b) )?"b is ok":"b fails";
alert(aIsInteger+"; "+bIsInteger);
2014年,我在IE8上测试了这一点,然后在Chrome上测试了2021,两者都返回“a是ok;b是fails”,这意味着如果一个数字太大,它就不能再是整数了。
引用一句经典的话,20位数字对任何人来说都应该足够了。
正如其他人提到的,你在JS中只有双打。那么,如何定义一个整数?只需检查舍入数字是否等于自身:
function isInteger(f) {
return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }
有一个名为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;
};