How do I check that a number is float or integer?

2018-12-31 03:48发布

How to find that a number is float or integer?

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

30条回答
旧时光的记忆
2楼-- · 2018-12-31 04:22

In java script all the numbers are internally 64 bit floating point, same as double in java. There are no diffrent types in javascript, all are represented by type number. Hence you wil l not be able make a instanceof check. However u can use the above solutions given to find out if it is a fractional number. designers of java script felt with a single type they can avoid numerous type cast errors.

查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 04:23

Why not something like this:

var isInt = function(n) { return parseInt(n) === n };
查看更多
千与千寻千般痛.
4楼-- · 2018-12-31 04:26

Here are efficient functions that check if the value is a number or can be safely converted to a number:

function isNumber(value) {
    if ((undefined === value) || (null === value)) {
        return false;
    }
    if (typeof value == 'number') {
        return true;
    }
    return !isNaN(value - 0);
}

And for integers (would return false if the value is a float):

function isInteger(value) {
    if ((undefined === value) || (null === value)) {
        return false;
    }
    return value % 1 == 0;
}

The efficiency here is that parseInt (or parseNumber) are avoided when the value already is a number. Both parsing functions always convert to string first and then attempt to parse that string, which would be a waste if the value already is a number.

Thank you to the other posts here for providing further ideas for optimization!

查看更多
看淡一切
5楼-- · 2018-12-31 04:27

For those curious, using Benchmark.js I tested the most up-voted answers (and the one posted today) on this post, here are my results:

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
查看更多
泪湿衣
6楼-- · 2018-12-31 04:28
function isInteger(x) { return typeof x === "number" && isFinite(x) && Math.floor(x) === x; }
function isFloat(x) { return !!(x % 1); }

// give it a spin

isInteger(1.0);        // true
isFloat(1.0);          // false
isFloat(1.2);          // true
isInteger(1.2);        // false
isFloat(1);            // false
isInteger(1);          // true    
isFloat(2e+2);         // false
isInteger(2e+2);       // true
isFloat('1');          // false
isInteger('1');        // false
isFloat(NaN);          // false
isInteger(NaN);        // false
isFloat(null);         // false
isInteger(null);       // false
isFloat(undefined);    // false
isInteger(undefined);  // false
查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 04:28

YourJS provides the following two functions which work for all numbers including returning false for -Infinity and Infinity:

function isFloat(x) {
  return typeOf(x, 'Number') && !!(x % 1);
}

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

Due to the fact that typeOf() is a YourJS internal function, if you wanted to use these definitions you can download the version for just these functions here: http://yourjs.com/snippets/build/34

查看更多
登录 后发表回答