如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
简单整数测试:
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位数字对任何人来说都应该足够了。
其他回答
function isInt(n)
{
return n != "" && !isNaN(n) && Math.round(n) == n;
}
function isFloat(n){
return n != "" && !isNaN(n) && Math.round(n) != n;
}
适用于所有情况。
尝试这些函数来测试一个值是否是一个没有小数部分的数字基元值,并且在可以表示为精确整数的大小范围内。
function isFloat(n) {
return n === +n && n !== (n|0);
}
function isInteger(n) {
return n === +n && n === (n|0);
}
下面的函数防止空字符串、未定义、空值和max/min值范围。Javascript引擎从一开始就应该内置这些函数。:)
享受
function IsInteger(iVal) {
var iParsedVal; //our internal converted int value
iParsedVal = parseInt(iVal,10);
if (isNaN(iParsedVal) || Infinity == iParsedVal || -Infinity == iParsedVal) //sanity check - guard against empty strings and max/min values
return false;
else
return Number(iVal) === (iParsedVal | 0); //the 2nd operand group (intValue | 0), evaluates to true only if the intValue is an integer; so an int type will only return true
}
function IsFloat(fVal) {
var fParsedVal; //our internal converted float value
fParsedVal = parseFloat(fVal);
if (isNaN(fParsedVal) || Infinity == fParsedVal || -Infinity == fParsedVal) //sanity check - guard against empty strings and max/min values
return false;
else
return !!(fVal % 1); //true only if there is a fractional value after the mod op; the !! returns the opposite value of the op which reflects the function's return value
}
以下是检查值是否为数字或是否可以安全地转换为数字的有效函数:
function isNumber(value) {
if ((undefined === value) || (null === value)) {
return false;
}
if (typeof value == 'number') {
return true;
}
return !isNaN(value - 0);
}
对于整数(如果值是浮点,则返回false):
function isInteger(value) {
if ((undefined === value) || (null === value)) {
return false;
}
return value % 1 == 0;
}
这里的效率是,当值已经是数字时,可以避免parseInt(或parseNumber)。这两个解析函数总是先转换为字符串,然后尝试解析该字符串,如果值已经是数字,这将是一种浪费。
感谢这里的其他帖子为优化提供了进一步的想法!
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');
}