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

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

当前回答

它真的不必那么复杂。整数的parseFloat()和parseInt()等价物的数值将相同。因此,您可以这样做:

function isInt(value){ 
    return (parseFloat(value) == parseInt(value)) && !isNaN(value);
}

Then

if (isInt(x)) // do work

这也将允许字符串检查,因此并不严格。如果想要一个强类型的解决方案(也就是,不使用字符串):

function is_int(value){ return !isNaN(parseInt(value * 1) }

其他回答

当除以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中被标准化。这个答案涵盖了这个解决方案。

下面的函数防止空字符串、未定义、空值和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
}

有时Number对象不允许您直接使用mod运算符(%),如果您面临这种情况,您可以使用此解决方案。

if(object instanceof Number ){
   if( ((Number) object).doubleValue() % 1 == 0 ){
      //your object is an integer
   }
   else{
      //your object is a double
   }
}

对于整数,我使用这个

function integer_or_null(value) {
    if ((undefined === value) || (null === value)) {
        return null;
    }
    if(value % 1 != 0) {
        return null;
    }
    return value;
}
var isInt = function (n) { return n === (n | 0); };

还没有这样的案例。