如何检查一个数字是浮点数还是整数?

859

如何判断一个数字是float还是integer

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

53
我理解您的问题,但是为了明确:<nit-pick> JavaScript没有不同的整数和浮点数字类型。在JavaScript中每个数字都只是一个Number</nit-pick> - Matt Ball
5
根据您的理解,“无穷大”是整数还是非整数?这里的答案在这个问题上分布得相当均匀。 - Mike Samuel
14
为了数学上的准确性:由于无限大不是实数,而所有整数都是实数,因此“无穷大”不能被视为整数。 - rvighne
2
@rvighne,我认为我们都同意无穷大和NaN不是实数的事实意味着IEEE-754浮点数不是实数的子集。所有基于IEEE-754的数值分析都必须处理这个事实。我不明白的是你如何认为这个事实决定了is_integral在基数方面应该如何行事。就个人而言,我认为((x%1)==0)是一个很好的代理,并且已经被IEEE-754完全指定,因此没有必要争论不同数字线之间的对应关系。 - Mike Samuel
5
你认为 1.0 是整型还是浮点型? - vol7ron
显示剩余7条评论
52个回答

1

使用此功能可以检查字符串或数字是否为“十进制”(正确的浮点数):

var IsDecimal = function(num){
    return ((num.toString().split('.').length) <= 2 && num.toString().match(/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/)) ? (!isNaN(Number.parseFloat(num))) : false ;
}

还有另一种方法可以检查字符串或数字是否为整数:

var IsInteger = function(num){
    return ((num.toString().split('.').length) == 1 && num.toString().match(/^[\-]?\d+$/)) ? (!isNaN(Number.parseInt(num))) : false ;
}

var IsDecimal = function(num){
    return ((num.toString().split('.').length) <= 2 && num.toString().match(/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/)) ? (!isNaN(Number.parseFloat(num))) : false ;
}

var IsInteger = function(num){
    return ((num.toString().split('.').length) == 1 && num.toString().match(/^[\-]?\d+$/)) ? (!isNaN(Number.parseInt(num))) : false ;
}


console.log("-------------- As string --------------");
console.log("Integers:");
console.log("0 = " + IsInteger("0"));
console.log("34 = " + IsInteger("34"));
console.log(".34 = " + IsInteger(".34"));
console.log("3.4 = " + IsInteger("3.4"));
console.log("3e = " + IsInteger("3e"));
console.log("e3 = " + IsInteger("e3"));
console.log("-34 = " + IsInteger("-34"));
console.log("--34 = " + IsInteger("--34"));
console.log("034 = " + IsInteger("034"));
console.log("0-34 = " + IsInteger("0-34"));
console.log("Floats/decimals:");
console.log("0 = " + IsDecimal("0"));
console.log("64 = " + IsDecimal("64"));
console.log(".64 = " + IsDecimal(".64"));
console.log("6.4 = " + IsDecimal("6.4"));
console.log("6e2 = " + IsDecimal("6e2"));
console.log("6e = " + IsDecimal("6e"));
console.log("e6 = " + IsDecimal("e6"));
console.log("-64 = " + IsDecimal("-64"));
console.log("--64 = " + IsDecimal("--64"));
console.log("064 = " + IsDecimal("064"));
console.log("0-64 = " + IsDecimal("0-64"));
console.log("\n-------------- As numbers --------------");
console.log("Integers:");
console.log("0 = " + IsInteger(0));
console.log("34 = " + IsInteger(34));
console.log(".34 = " + IsInteger(0.34));
console.log("3.4 = " + IsInteger(3.4));
console.log("-34 = " + IsInteger(-34));
console.log("034 = " + IsInteger(034));
console.log("0-34 = " + IsInteger(0-34));
console.log("Floats/decimals:");
console.log("0 = " + IsDecimal(0));
console.log("64 = " + IsDecimal(64));
console.log(".64 = " + IsDecimal(0.64));
console.log("6.4 = " + IsDecimal(6.4));
console.log("6e2 = " + IsDecimal(6e2));
console.log("-64 = " + IsDecimal(-64));
console.log("064 = " + IsDecimal(064));
console.log("0-64 = " + IsDecimal(0-64));


1

要检查数字是否为整数并使用2位小数格式,您可以在React-Native中使用以下公式。

isInt = (n) => {
        return n % 1 === 0;
     }

    show = (x) => {
        if(x) {
           if (this.isInt(x)) {
               return ${x} 
           }
           else {
            return ${x.toFixed(2)}
           }
        }
    }

1
我来晚了,但这是我的版本。
isInteger: obj => Number.isInteger(!isNaN(obj % 1) && obj % 1 !== 0 ? obj : parseInt(obj)),

1

我喜欢这个小函数,它会针对正数和负数都返回true:

function isInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN(val+".0");
}

这段代码能够正常工作是因为1或"1"会变成"1.0",而isNaN()会返回false(我们再对其取反并返回),但是1.0或"1.0"会变成"1.0.0",而"string"会变成"string.0",它们都不是数字,所以isNaN()会返回false(同样被取反)。
如果你只想要正整数,可以使用以下变体:
function isPositiveInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN("0"+val);
}

或者,对于负整数:
function isNegativeInt(val) {
    return `["string","number"].indexOf(typeof(val)) > -1` && val !== '' && isNaN("0"+val);
}

isPositiveInt()函数通过将连接的数字字符串移到要测试的值之前来工作。例如,isPositiveInt(1)的结果是isNaN()评估"01",这将得出false。同时,isPositiveInt(-1)的结果是isNaN()评估"0-1",这将得出true。我们否定返回值,这就给了我们想要的结果。isNegativeInt()的工作方式类似,但不否定isNaN()的返回值。

编辑:

我的原始实现也会在数组和空字符串上返回true。此实现没有这个缺陷。它还具有如果val不是字符串或数字,或者是空字符串则提前返回的好处,在这些情况下更快。您可以通过替换前两个子句来进一步修改它

typeof(val) != "number"

如果您只想匹配字面数字(而不是字符串)

编辑:

我还不能发表评论,所以我将其添加到我的答案中。@Asok发布的基准测试非常有信息量;但是,最快的函数不符合要求,因为它也返回浮点数、数组、布尔值和空字符串的TRUE。

我创建了以下测试套件来测试每个函数,还将我的答案添加到列表中(函数8解析字符串,函数9不解析):

funcs = [
    function(n) {
        return n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
    },
    function(n) {
        return n.toString().indexOf('.') === -1;
    },
    function(n) {
        return n === +n && n === (n|0);
    },
    function(n) {
        return parseInt(n) === n;
    },
    function(n) {
        return /^-?[0-9]+$/.test(n.toString());
    },
    function(n) {
        if ((undefined === n) || (null === n)) {
            return false;
        }
        if (typeof n == 'number') {
            return true;
        }
        return !isNaN(n - 0);
    },
    function(n) {
        return ["string","number"].indexOf(typeof(n)) > -1 && n !== '' && !isNaN(n+".0");
    }
];
vals = [
    [1,true],
    [-1,true],
    [1.1,false],
    [-1.1,false],
    [[],false],
    [{},false],
    [true,false],
    [false,false],
    [null,false],
    ["",false],
    ["a",false],
    ["1",null],
    ["-1",null],
    ["1.1",null],
    ["-1.1",null]
];

for (var i in funcs) {
    var pass = true;
    console.log("Testing function "+i);
    for (var ii in vals) {
        var n = vals[ii][0];
        var ns;
        if (n === null) {
            ns = n+"";
        } else {
            switch (typeof(n)) {
                case "string":
                    ns = "'" + n + "'";
                    break;
                case "object":
                    ns = Object.prototype.toString.call(n);
                    break;
                default:
                    ns = n;
            }
            ns = "("+typeof(n)+") "+ns;
        }

        var x = vals[ii][1];
        var xs;
        if (x === null) {
            xs = "(ANY)";
        } else {
            switch (typeof(x)) {
                case "string":
                    xs = "'" + n + "'";
                    break;
                case "object":
                    xs = Object.prototype.toString.call(x);
                    break;
                default:
                    xs = x;
            }
            xs = "("+typeof(x)+") "+xs;
        }

        var rms;
        try {
            var r = funcs[i](n);
            var rs;
            if (r === null) {
                rs = r+"";
            } else {
                switch (typeof(r)) {
                    case "string":
                        rs = "'" + r + "'";
                        break;
                    case "object":
                        rs = Object.prototype.toString.call(r);
                        break;
                    default:
                        rs = r;
                }
                rs = "("+typeof(r)+") "+rs;
            }

            var m;
            var ms;
            if (x === null) {
                m = true;
                ms = "N/A";
            } else if (typeof(x) == 'object') {
                m = (xs === rs);
                ms = m;
            } else {
                m = (x === r);
                ms = m;
            }
            if (!m) {
                pass = false;
            }
            rms = "Result: "+rs+", Match: "+ms;
        } catch (e) {
            rms = "Test skipped; function threw exception!"
        }

        console.log("    Value: "+ns+", Expect: "+xs+", "+rms);
    }
    console.log(pass ? "PASS!" : "FAIL!");
}

我还将函数 #8 添加到测试列表中重新运行了基准测试。由于结果有点尴尬(即该函数并不快速),因此我不会发布结果...

缩略的测试结果如下所示(我删除了成功的测试,因为输出内容很长):

Testing function 0
Value: (object) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 1
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 2
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 3
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) 'a', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 4
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 5
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 6
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 7
Value: (number) 1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (number) -1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
FAIL!

Testing function 8
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 9
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

我已经保留了失败结果,这样你就可以看到每个函数失败的地方,并且使用了(string) '#'测试,这样你就可以看到每个函数如何处理字符串中的整数和浮点数值,因为有些人可能希望将它们解析为数字,而有些人则不希望。
在测试的10个函数中,实际符合OP要求的是[1,3,5,6,8,9]。

1

对于那些好奇的人,我使用Benchmark.js测试了这篇文章中得到最多赞的答案(以及今天发布的答案),以下是我的测试结果:

var n = -10.4375892034758293405790;
var suite = new Benchmark.Suite;
suite
    // kennebec
    .add('0', function() {
        return n % 1 == 0;
    })
    // kennebec
    .add('1', function() {
        return typeof n === 'number' && n % 1 == 0;
    })
    // kennebec
    .add('2', function() {
        return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
    })

    // Axle
    .add('3', function() {
        return n.toString().indexOf('.') === -1;
    })

    // Dagg Nabbit
    .add('4', function() {
        return n === +n && n === (n|0);
    })

    // warfares
    .add('5', function() {
        return parseInt(n) === n;
    })

    // Marcio Simao
    .add('6', function() {
        return /^-?[0-9]+$/.test(n.toString());
    })

    // Tal Liron
    .add('7', function() {
        if ((undefined === n) || (null === n)) {
            return false;
        }
        if (typeof n == 'number') {
            return true;
        }
        return !isNaN(n - 0);
    });

// Define logs and Run
suite.on('cycle', function(event) {
    console.log(String(event.target));
}).on('complete', function() {
    console.log('Fastest is ' + this.filter('fastest').pluck('name'));
}).run({ 'async': true });

0 x 12,832,357 ops/sec ±0.65% (90 runs sampled)
1 x 12,916,439 ops/sec ±0.62% (95 runs sampled)
2 x 2,776,583 ops/sec ±0.93% (92 runs sampled)
3 x 10,345,379 ops/sec ±0.49% (97 runs sampled)
4 x 53,766,106 ops/sec ±0.66% (93 runs sampled)
5 x 26,514,109 ops/sec ±2.72% (93 runs sampled)
6 x 10,146,270 ops/sec ±2.54% (90 runs sampled)
7 x 60,353,419 ops/sec ±0.35% (97 runs sampled)

Fastest is 7 Tal Liron

1

可以使用Number.isInteger(number)来检查这一点。在Internet Explorer中不起作用,但该浏览器已不再使用。如果您需要将像“90”这样的字符串转换为整数(这不是问题),请尝试Number.isInteger(Number(number))。 "官方"的isInteger认为9.0是一个整数,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number。 在旧版浏览器中,大多数答案似乎都是正确的,但现代浏览器已经进步了,实际上支持浮点整数检查。


1
在JavaScript中,所有数字都是内部64位浮点数,与Java中的double相同。JavaScript中没有不同类型,所有类型都由number类型表示。因此,您将无法进行instanceof检查。但是,您可以使用上述解决方案来找出它是否为分数。JavaScript的设计者们认为,通过使用单一类型,他们可以避免许多类型转换错误。

1
function int(a) {
  return a - a === 0 && a.toString(32).indexOf('.') === -1
}

function float(a) {
  return a - a === 0 && a.toString(32).indexOf('.') !== -1
}

如果你想排除字符串,可以添加typeof a === 'number'

1

浮动

var decimal=  /^[-+]?[0-9]+\.[0-9]+$/; 

if (!price.match(decimal)) {
      alert('Please enter valid float');
      return false;
    }

对于整数

var number = /^\d+$/; 

if (!price.match(number)) {
      alert('Please enter valid integer');
      return false;
    }

1
你可以使用Number.isInteger()方法来检查数字是整数还是浮点数,例如通过除法:
    function isNumberFloatOrInteger(a, b){
     if(Number.isInteger(a / b)){
      return true;
      }
      else{ return false };
}

注意:isInteger() 不兼容 Internet Explorer。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接