如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
这可能不如%answer的性能好,它可以防止您首先转换为字符串,但我还没有看到任何人发布它,所以这里有另一个选项应该可以正常工作:
function isInteger(num) {
return num.toString().indexOf('.') === -1;
}
其他回答
这真的取决于你想要实现什么。如果你想“模仿”强类型语言,那么我建议你不要尝试。正如其他人提到的,所有数字都有相同的表示(相同类型)。
使用Claudiu提供的内容:
isInteger(1.0)->true
这看起来很正常,但在C这样的情况下,你会错
这是我的:
function isInt(quale) {
var valore = $('#'+quale).val().toLowerCase();
if (isNaN(Number(String(valore))) || (valore.indexOf("e") > 0)) {
// Not int
} else {
// Is Int!
}
}
还有这个:
function isFloat(quale) {
var valore = $('#'+quale).val();
valore = valore.replace(",", "");
if (isNaN(String(valore)) || (valore.indexOf("e") > 0)) {
// Not Float
} else {
// Float
}
}
Ad majora!
正如其他人提到的,你在JS中只有双打。那么,如何定义一个整数?只需检查舍入数字是否等于自身:
function isInteger(f) {
return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }
基于我在这里看到的所有内容,我创建了自己的一组函数来测试我所需要的:
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的解决方案更短,检查更少,因此可能是更好的解决方案。
简单整数测试:
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位数字对任何人来说都应该足够了。