如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
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
其他回答
试试这个
let n;
return (n = value % 1) !== 0 && !isNaN(n);
当返回值为false时,表示输入值为浮点数或浮点数字符串,否则输入值为整数numref或整数字符串。
基本上,它需要检查精度值是否不等于零。
另一个是检查正确的字符串编号。
我们可以通过isInteger函数进行检查。ie number将返回true,float返回false
console.log(Number.isIInteger(2)),<BR>将返回true
console.log(Number.isInteger(2.5))将返回false
!!(24%1) // false
!!(24.2%1) // true
function isInteger(n) {
return ((typeof n==='number')&&(n%1===0));
}
function isFloat(n) {
return ((typeof n==='number')&&(n%1!==0));
}
function isNumber(n) {
return (typeof n==='number');
}
这真的取决于你想要实现什么。如果你想“模仿”强类型语言,那么我建议你不要尝试。正如其他人提到的,所有数字都有相同的表示(相同类型)。
使用Claudiu提供的内容:
isInteger(1.0)->true
这看起来很正常,但在C这样的情况下,你会错