如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
2022年更新-我们可以简单地使用Number的方法。
检查整数或浮点:数字.is有限(val)
检查整数是否:数字.isInteger(val)
检查float(非整数):!Number.isInteger(val)&&Number.isFinite(val)
其他回答
这是我的:
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!
在java脚本中,所有数字都是内部64位浮点,与java中的double相同。javascript中没有不同的类型,所有类型都由类型号表示。因此,您将无法进行检查实例。然而,你可以使用上面给出的解来确定它是否是一个分数。java脚本的设计者认为,只要使用一种类型,就可以避免大量的类型转换错误。
您可以使用Number.isInteger()方法通过对数字进行除法来检查数字是整数还是浮点数,例如:
function isNumberFloatOrInteger(a, b){
if(Number.isInteger(a / b)){
return true;
}
else{ return false };
}
注意:isInteger()与internet explorer不兼容。
要检查数字是否为Int并应用2十进制格式,可以在React Native中使用以下公式。
isInt = (n) => {
return n % 1 === 0;
}
show = (x) => {
if(x) {
if (this.isInt(x)) {
return ${x}
}
else {
return ${x.toFixed(2)}
}
}
}
这是检查INT和FLOAT的最终代码
function isInt(n) {
if(typeof n == 'number' && Math.Round(n) % 1 == 0) {
return true;
} else {
return false;
}
}
OR
function isInt(n) {
return typeof n == 'number' && Math.Round(n) % 1 == 0;
}