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

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;   
}   

其他回答

这是我的代码。它检查以确保它不是空字符串(否则将传递),然后将其转换为数字格式。现在,取决于您是否希望“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;

};

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

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

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

我们可以通过isInteger函数进行检查。ie number将返回true,float返回false

console.log(Number.isIInteger(2)),<BR>将返回true

console.log(Number.isInteger(2.5))将返回false

这是检查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;   
}   

试试这个

let n;
return (n = value % 1) !== 0 && !isNaN(n);

当返回值为false时,表示输入值为浮点数或浮点数字符串,否则输入值为整数numref或整数字符串。

基本上,它需要检查精度值是否不等于零。

另一个是检查正确的字符串编号。