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

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

当前回答

对于那些好奇的人,我使用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

其他回答

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

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

如果要排除字符串,可以添加类型a==“number”。

比较floor()结果与ceil()结果不同。

const isFloat = v => Math.floor(v) !== Math.ceil(v);
> isFloat(1)
= false

> isFloat(1.1)
= true

> isFloat(42)
= false

> isFloat(84.42)
= true

可以使用简单的正则表达式:

function isInt(value) {

    var er = /^-?[0-9]+$/;

    return er.test(value);
}

或者,您也可以根据需要使用以下功能。它们由PHPJS项目开发。

is_int()=>检查变量类型是否为整数,其内容是否为整数

is_float()=>检查变量类型是否为float,其内容是否为floate

ctype_digit()=>检查变量类型是否为字符串,以及其内容是否只有小数位数

更新1

现在它也检查负数,感谢@ChrisBartley的评论!

try this one
function amountcheck()
    {
        var dpamt=$('#dpamt').val()/5000;
        var ints=dpamt.toString();
        var isint=ints.split('.');
        if(isint[1]>0)
        {
            alert('float value');
            return false;
        }
        else
        {   
            alert('int value');
        }
    }

尝试这些函数来测试一个值是否是一个没有小数部分的数字基元值,并且在可以表示为精确整数的大小范围内。

function isFloat(n) {
    return n === +n && n !== (n|0);
}

function isInteger(n) {
    return n === +n && n === (n|0);
}