如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
下面的函数防止空字符串、未定义、空值和max/min值范围。Javascript引擎从一开始就应该内置这些函数。:)
享受
function IsInteger(iVal) {
var iParsedVal; //our internal converted int value
iParsedVal = parseInt(iVal,10);
if (isNaN(iParsedVal) || Infinity == iParsedVal || -Infinity == iParsedVal) //sanity check - guard against empty strings and max/min values
return false;
else
return Number(iVal) === (iParsedVal | 0); //the 2nd operand group (intValue | 0), evaluates to true only if the intValue is an integer; so an int type will only return true
}
function IsFloat(fVal) {
var fParsedVal; //our internal converted float value
fParsedVal = parseFloat(fVal);
if (isNaN(fParsedVal) || Infinity == fParsedVal || -Infinity == fParsedVal) //sanity check - guard against empty strings and max/min values
return false;
else
return !!(fVal % 1); //true only if there is a fractional value after the mod op; the !! returns the opposite value of the op which reflects the function's return value
}
其他回答
我喜欢这个小函数,它对正整数和负整数都会返回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]
对于那些好奇的人,我使用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 isInt(number) {
if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
return !(number - parseInt(number));
}
function isFloat(number) {
if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
return number - parseInt(number) ? true : false;
}
var测试={“integer”:1,“浮动”:1.1,“整数InString”:“5”,“floatInString”:“5.5”,“负Int”:-345,“负浮动”:-34.98,“negativeIntString”:“-45”,“negativeFloatString”:“-23.09”,“notValidFalse”:false,“notValidTrue”:true,“notValidString”:“45lorem”,“notValidStringFloat”:“4.5lorem”,'notValidNan':NaN,“notValidObj”:{},“notValidArr”:[1,2],};函数isInt(数字){如果(!/^[“|']{0,1}[-]{0.1}\d{0,}(\.{0,1}\d+)[“|']{0 1}$/.test(数字))返回false;回来(number-parseInt(number));}函数isFloat(数字){如果(!/^[“|']{0,1}[-]{0.1}\d{0,}(\.{0,1}\d+)[“|']{0 1}$/.test(数字))返回false;返回number-parseInt(number)?真:假;}函数测试函数(obj){var keys=对象.keys(obj);var values=对象.值(obj);values.forEach(函数(元素,索引){console.log(`${keys[index]}(${element})var是整数吗${isInt(元素)}`);console.log(`${keys[index]}(${element})var是浮点数吗${isFloat(元素)}`);});}testFunctions(测试);
我知道已经有30个答案,但一个复杂的方法是这样做:
function isInteger(n) {
return n.toString().split('.').length === 1;
}
解释:我们首先将n转换为字符串,然后基于点拆分它。如果n是浮点,如4.5,则拆分将返回数组['4','5']。如果它是像45这样的整数,它将返回['45']。因此,如果数组的长度是1,那么我们知道它是一个数字。
注:如果您想以新的ES6格式(箭头函数)编写此函数:
const isInteger = n => n.toString().split('.').length === 1;
有一个名为Number.isInteger()的方法,它目前在除IE.MDN之外的所有浏览器中都实现了。MDN还为其他浏览器提供了一个polyfill:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value;
};
但是,对于大多数使用情况,最好使用Number.isSafeInteger,它还可以检查值是否太高/太低,以至于任何小数点都会丢失。MDN也为此提供了一种聚菲。(您还需要上面的isInteger民意测验。)
if (!Number.MAX_SAFE_INTEGER) {
Number.MAX_SAFE_INTEGER = 9007199254740991; // Math.pow(2, 53) - 1;
}
Number.isSafeInteger = Number.isSafeInteger || function (value) {
return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
};