How to find that a number is float
or integer
?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
<
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