如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
我需要检查一个输入值,如果它是整数或浮点值,为此我想出了以下方法:
函数isInteger(x){var整数=parseInt(x,10);如果(!isNaN(整数)&&!isFloat(x)){返回true;}return false;}函数isFloat(x){var f=parseFloat(x);var floor=数学楼层(f);var分数=f-地板;如果(分数>0){返回true;}return false;}var案例=["1","1.00","1.01","0.05",“ab1”,“ab1.1”,1.1.00,1.01,0.05,1e+5,"",真的,假,无效的NaN,未定义,];console.log(“isInteger()”);对于(var i=0;i<cases.length;i++){console.log(cases[i],isInteger(cases[i]));}console.log(“\nisFloat()”);对于(var i=0;i<cases.length;i++){console.log(cases[i],isFloat(cases[i]));}
其他回答
当除以1时检查余数:
function isInt(n) {
return n % 1 === 0;
}
如果你不知道参数是一个数字,你需要两个测试:
function isInt(n){
return Number(n) === n && n % 1 === 0;
}
function isFloat(n){
return Number(n) === n && n % 1 !== 0;
}
2019年更新在这个答案写出来5年后,一个解决方案在ECMA脚本2015中被标准化。这个答案涵盖了这个解决方案。
浮动验证条件:
if (lnk.value == +lnk.value && lnk.value != (lnk.value | 0))
整数验证条件:
if (lnk.value == +lnk.value && lnk.value == (lnk.value | 0))
希望这可能会有所帮助。
以下是检查值是否为数字或是否可以安全地转换为数字的有效函数:
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)。这两个解析函数总是先转换为字符串,然后尝试解析该字符串,如果值已经是数字,这将是一种浪费。
感谢这里的其他帖子为优化提供了进一步的想法!
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') );
这是我的代码。它检查以确保它不是空字符串(否则将传递),然后将其转换为数字格式。现在,取决于您是否希望“1.1”等于1.1,这可能是您想要的,也可能不是您想要的。
var isFloat = function(n) {
n = n.length > 0 ? Number(n) : false;
return (n === parseFloat(n));
};
var isInteger = function(n) {
n = n.length > 0 ? Number(n) : false;
return (n === parseInt(n));
};
var isNumeric = function(n){
if(isInteger(n) || isFloat(n)){
return true;
}
return false;
};