如何发现一个数字是浮点数或整数?

1.25 --> float  
1 --> integer  
0 --> integer  
0.25 --> float

当前回答

这是检查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(n) 
{
    return n != "" && !isNaN(n) && Math.round(n) == n;
}
function isFloat(n){
    return n != "" && !isNaN(n) && Math.round(n) != n;
}

适用于所有情况。

以下是检查值是否为数字或是否可以安全地转换为数字的有效函数:

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)。这两个解析函数总是先转换为字符串,然后尝试解析该字符串,如果值已经是数字,这将是一种浪费。

感谢这里的其他帖子为优化提供了进一步的想法!

2022年更新-我们可以简单地使用Number的方法。

检查整数或浮点:数字.is有限(val)

检查整数是否:数字.isInteger(val)

检查float(非整数):!Number.isInteger(val)&&Number.isFinite(val)

您可以使用Number.isInteger()方法通过对数字进行除法来检查数字是整数还是浮点数,例如:

    function isNumberFloatOrInteger(a, b){
     if(Number.isInteger(a / b)){
      return true;
      }
      else{ return false };
}

注意:isInteger()与internet explorer不兼容。

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') );