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

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

当前回答

这是我能想到的浮点和整数检查的最佳解决方案。

函数isFloat(n){如果(!n){return false}回来isNaN(n%1)&&n%1!==0;}函数isInt(n){如果(n长度==0){return false}回来isNaN(n%1)&&n%1==0;}

其他回答

要检查数字是否为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)}
           }
        }
    }
var isInt = function (n) { return n === (n | 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!

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

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

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

正如其他人提到的,你在JS中只有双打。那么,如何定义一个整数?只需检查舍入数字是否等于自身:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }