如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
另一种方法是:
function isFloat(float) {
return /\./.test(float.toString());
}
可能没有其他方法有效,但另一种方法仍然有效。
其他回答
基于我在这里看到的所有内容,我创建了自己的一组函数来测试我所需要的:
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的解决方案更短,检查更少,因此可能是更好的解决方案。
下面的函数防止空字符串、未定义、空值和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
}
试试这个
let n;
return (n = value % 1) !== 0 && !isNaN(n);
当返回值为false时,表示输入值为浮点数或浮点数字符串,否则输入值为整数numref或整数字符串。
基本上,它需要检查精度值是否不等于零。
另一个是检查正确的字符串编号。
这是检查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;
}
这是我的:
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!