提问人:Electrons_Ahoy 提问时间:10/7/2008 最后编辑:LiamElectrons_Ahoy 更新时间:5/4/2023 访问量:1622335
如何检查字符串是否为有效数字?
How can I check if a string is a valid number?
答:
尝试 isNan 函数:
isNaN() 函数确定值是否为非法数字 (Not-a-Number)。
如果值等于 NaN,则此函数返回 true。否则,它将返回 false。
此函数不同于特定于 Number 的 Number.isNaN() 方法。
全局 isNaN() 函数,将测试值转换为 Number,然后对其进行测试。
Number.isNan() 不会将值转换为 Number,并且不会对任何不是 Number 类型的值返回 true...
评论
isNaN()
false
parseInt(),但请注意,这个函数在某种意义上有点不同,例如它为 parseInt(“100px”) 返回 100。
评论
parseInt(09)
paraseInt(09, 10)
你可以采用正则表达式的方式:
var num = "987238";
if(num.match(/^-?\d+$/)){
//valid integer (positive or negative)
}else if(num.match(/^\d+\.\d+$/)){
//valid float
}else{
//not valid number
}
评论
2020 年 10 月 2 日:请注意,许多基本方法都充满了微妙的错误(例如空格、隐式部分解析、基数、数组强制等),这里的许多答案都没有考虑到这些错误。以下实现可能适合您,但请注意,它不适用于小数点“”以外的数字分隔符:.
function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
要检查变量(包括字符串)是否为数字,请检查它是否为数字:
无论变量内容是字符串还是数字,这都有效。
isNaN(num) // returns true if the variable does NOT contain a valid number
例子
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
isNaN('') // false
isNaN(' ') // false
isNaN(false) // false
当然,如果需要,您可以否定这一点。例如,要实现您给出的示例,请执行以下操作:IsNumeric
function isNumeric(num){
return !isNaN(num)
}
要将包含数字的字符串转换为数字,请执行以下操作:
仅当字符串仅包含数字字符时才有效,否则返回 .NaN
+num // returns the numeric value of the string, or NaN
// if the string isn't purely numeric characters
例子
+'12' // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN
将字符串松散地转换为数字
用于将“12px”转换为 12,例如:
parseInt(num) // extracts a numeric value from the
// start of the string, or NaN.
例子
parseInt('12') // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last three may
parseInt('12a5') // 12 be different from what
parseInt('0x10') // 16 you expected to see.
浮
请记住,与 不同,(顾名思义)将通过砍掉小数点后的所有内容将浮点数转换为整数(如果您因为这种行为而想使用,最好使用另一种方法):+num
parseInt
parseInt()
+'12.345' // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12
空字符串
空字符串可能有点违反直觉。 将空字符串或带空格的字符串转换为零,并假定相同:+num
isNaN()
+'' // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false
但不同意:parseInt()
parseInt('') // NaN
parseInt(' ') // NaN
评论
isNaN
isNaN
var n = 'a'; if (+n === +n) { // is number }
isNaN(1 + false + parseInt("1.do you trust your users?"))
报价:
isNaN(num) // 如果变量不包含有效数字,则返回 true
如果您需要检查前导/尾随空格,则不完全正确 - 例如,当需要一定数量的数字时,并且您需要获得“1111”而不是“111”或“111”作为 PIN 输入。
更好用:
var num = /^\d+$/.test(num)
评论
'-1'
'0.1'
'1e10'
老问题,但给出的答案中缺少几点。
科学记数法。
!isNaN('1e+30')
是 ,但是在大多数情况下,当人们询问数字时,他们不想匹配 .true
1e+30
大浮点数可能表现得很奇怪
观察(使用 Node.js):
> var s = Array(16 + 1).join('9')
undefined
> s.length
16
> s
'9999999999999999'
> !isNaN(s)
true
> Number(s)
10000000000000000
> String(Number(s)) === s
false
>
另一方面:
> var s = Array(16 + 1).join('1')
undefined
> String(Number(s)) === s
true
> var s = Array(15 + 1).join('9')
undefined
> String(Number(s)) === s
true
>
因此,如果有人期望 ,那么最好将字符串限制为最多 15 位(省略前导零之后)。String(Number(s)) === s
无限
> typeof Infinity
'number'
> !isNaN('Infinity')
true
> isFinite('Infinity')
false
>
鉴于所有这些,检查给定的字符串是否是满足以下所有条件的数字:
- 非科学记数法
- 可预测的转换
Number
String
- 有限的
这不是一件容易的事。这是一个简单的版本:
function isNonScientificNumberString(o) {
if (!o || typeof o !== 'string') {
// Should not be given anything but strings.
return false;
}
return o.length <= 15 && o.indexOf('e+') < 0 && o.indexOf('E+') < 0 && !isNaN(o) && isFinite(o);
}
然而,即使是这个也远未完成。这里不处理前导零,但它们确实搞砸了长度测试。
评论
PFB工作解决方案:
function(check){
check = check + "";
var isNumber = check.trim().length>0? !isNaN(check):false;
return isNumber;
}
如果你只是想检查一个字符串是否是一个整数(没有小数位),正则表达式是一个不错的方法。其他方法对于如此简单的事情来说太复杂了。isNaN
function isNumeric(value) {
return /^-?\d+$/.test(value);
}
console.log(isNumeric('abcd')); // false
console.log(isNumeric('123a')); // false
console.log(isNumeric('1')); // true
console.log(isNumeric('1234567890')); // true
console.log(isNumeric('-23')); // true
console.log(isNumeric(1234)); // true
console.log(isNumeric(1234n)); // true
console.log(isNumeric('123.4')); // false
console.log(isNumeric('')); // false
console.log(isNumeric(undefined)); // false
console.log(isNumeric(null)); // false
若要仅允许正整数,请使用以下命令:
function isNumeric(value) {
return /^\d+$/.test(value);
}
console.log(isNumeric('123')); // true
console.log(isNumeric('-23')); // false
评论
/^[0-9]+$/.test(value)
在将参数传递给其构造函数时,可以使用 Number 的结果。
如果参数(字符串)无法转换为数字,则返回 NaN,因此您可以确定提供的字符串是否为有效数字。
注意:注意传递空字符串或和 as Number 时将返回 0;传递 true 将返回 1,false 返回 0。'\t\t'
'\n\t'
Number('34.00') // 34
Number('-34') // -34
Number('123e5') // 12300000
Number('123e-5') // 0.00123
Number('999999999999') // 999999999999
Number('9999999999999999') // 10000000000000000 (integer accuracy up to 15 digit)
Number('0xFF') // 255
Number('Infinity') // Infinity
Number('34px') // NaN
Number('xyz') // NaN
Number('true') // NaN
Number('false') // NaN
// cavets
Number(' ') // 0
Number('\t\t') // 0
Number('\n\t') // 0
评论
Number
+x
Number()
Number.parseFloat()
Number.parseInt()
如果你真的想确保一个字符串只包含一个数字、任何数字(整数或浮点数)和一个数字,你不能使用 / 、 或单独使用。请注意,实际上是返回 何时返回一个数字,以及何时返回 ,因此我将将其排除在讨论的其余部分之外。parseInt()
parseFloat()
Number()
!isNaN()
!isNaN()
true
Number()
false
NaN
问题在于,如果字符串包含任何数字,它将返回一个数字,即使该字符串不只包含一个数字:parseFloat()
parseFloat("2016-12-31") // returns 2016
parseFloat("1-1") // return 1
parseFloat("1.2.3") // returns 1.2
问题是,如果传递的值根本不是数字,它将返回一个数字!Number()
Number("") // returns 0
Number(" ") // returns 0
Number(" \u00A0 \t\n\r") // returns 0
滚动自己的正则表达式的问题在于,除非您创建确切的正则表达式来匹配 Javascript 识别的浮点数,否则您将错过案例或识别不应该识别的案例。即使您可以推出自己的正则表达式,为什么?有更简单的内置方法可以做到这一点。
然而,事实证明,(和)在不应该返回数字时返回数字的每种情况下都是正确的,反之亦然。因此,要确定字符串是否真的是确切的,并且只是一个数字,请调用这两个函数并查看它们是否都返回 true:Number()
isNaN()
parseFloat()
function isNumber(str) {
if (typeof str != "string") return false // we only process strings!
// could also coerce to string: str = ""+str
return !isNaN(str) && !isNaN(parseFloat(str))
}
评论
' 1'
'2 '
' 3 '
isNumber
如果有人走到这一步,我花了一些时间试图修补这个时刻.js(https://github.com/moment/moment)。这是我从中学到的东西:
function isNumeric(val) {
var _val = +val;
return (val !== val + 1) //infinity check
&& (_val === +val) //Cute coercion check
&& (typeof val !== 'object') //Array/object check
}
处理以下情况:
真!:
isNumeric("1"))
isNumeric(1e10))
isNumeric(1E10))
isNumeric(+"6e4"))
isNumeric("1.2222"))
isNumeric("-1.2222"))
isNumeric("-1.222200000000000000"))
isNumeric("1.222200000000000000"))
isNumeric(1))
isNumeric(0))
isNumeric(-0))
isNumeric(1010010293029))
isNumeric(1.100393830000))
isNumeric(Math.LN2))
isNumeric(Math.PI))
isNumeric(5e10))
假!:
isNumeric(NaN))
isNumeric(Infinity))
isNumeric(-Infinity))
isNumeric())
isNumeric(undefined))
isNumeric('[1,2,3]'))
isNumeric({a:1,b:2}))
isNumeric(null))
isNumeric([1]))
isNumeric(new Date()))
具有讽刺意味的是,我最挣扎的是:
isNumeric(new Number(1)) => false
欢迎任何建议。:]
评论
isNumeric(' ')
isNumeric('')
&& (val.replace(/\s/g,'') !== '') //Empty && (val.slice(-1) !== '.') //Decimal without Number
也许有一两个人遇到这个问题,他们需要比平时更严格的检查(就像我一样)。在这种情况下,这可能很有用:
if(str === String(Number(str))) {
// it's a "perfectly formatted" number
}
小心!这将拒绝像 、 、 、 这样的字符串。这是非常挑剔的 - 字符串必须与数字的“最小完美形式”匹配,才能通过此测试。.1
40.000
080
00.1
它使用 and 构造函数将字符串转换为一个数字,然后再转换回来,从而检查 JavaScript 引擎的“完美最小形式”(它通过初始构造函数转换为的格式)是否与原始字符串匹配。String
Number
Number
评论
(str === String(Math.round(Number(str))))
"Infinity"
"-Infinity"
"NaN"
Number.isFinite
str === ("" + +str)
0.000001
0.0000001
1e-7
1e10
我已经测试过了,迈克尔的解决方案是最好的。在上面为他的答案投票(在此页面搜索“如果你真的想确保一个字符串”以找到它)。从本质上讲,他的答案是这样的:
function isNumeric(num){
num = "" + num; //coerce num to be a string
return !isNaN(num) && !isNaN(parseFloat(num));
}
它适用于每个测试用例,我在这里记录了这些用例:https://jsfiddle.net/wggehvp9/5/
对于这些边缘情况,许多其他解决方案都失败了: ' '、null、“”、true 和 []。 从理论上讲,您可以使用它们,并进行适当的错误处理,例如:
return !isNaN(num);
或
return (+num === +num);
特殊处理 /\s/、null、“”、true、false、[](还有其他?
评论
为什么jQuery的实现不够好?
function isNumeric(a) {
var b = a && a.toString();
return !$.isArray(a) && b - parseFloat(b) + 1 >= 0;
};
迈克尔提出了这样的建议(尽管我在这里窃取了“user1691651 - John”的更改版本):
function isNumeric(num){
num = "" + num; //coerce num to be a string
return !isNaN(num) && !isNaN(parseFloat(num));
}
以下是最有可能性能不佳但结果可靠的解决方案。它是根据 jQuery 1.12.4 实现和 Michael 的答案制作的装置,对前导/尾随空格进行了额外的检查(因为 Michael 的版本对带有前导/尾随空格的数值返回 true):
function isNumeric(a) {
var str = a + "";
var b = a && a.toString();
return !$.isArray(a) && b - parseFloat(b) + 1 >= 0 &&
!/^\s+|\s+$/g.test(str) &&
!isNaN(str) && !isNaN(parseFloat(str));
};
不过,后一个版本有两个新变量。可以通过以下方式绕过其中之一:
function isNumeric(a) {
if ($.isArray(a)) return false;
var b = a && a.toString();
a = a + "";
return b - parseFloat(b) + 1 >= 0 &&
!/^\s+|\s+$/g.test(a) &&
!isNaN(a) && !isNaN(parseFloat(a));
};
我没有测试过其中任何一个,除了手动测试我当前困境中将遇到的几个用例之外,其他方式都是非常标准的东西。这是一种“站在巨人肩膀上”的情况。
我喜欢这个的简单性。
Number.isNaN(Number(value))
以上是常规的 Javascript,但我将其与打字稿 typeguard 结合使用以进行智能类型检查。这对于打字稿编译器非常有用,可以为您提供正确的智能感知,并且不会出现类型错误。
打字稿打字板
警告:请参阅下面的 Jeremy 评论。这在某些值上存在一些问题,我现在没有时间修复它,但是使用打字稿 typeguard 的想法很有用,所以我不会删除此部分。
isNotNumber(value: string | number): value is string {
return Number.isNaN(Number(this.smartImageWidth));
}
isNumber(value: string | number): value is number {
return Number.isNaN(Number(this.smartImageWidth)) === false;
}
假设您有一个属性,它是 .您可能希望根据它是否是字符串来执行逻辑。width
number | string
var width: number|string;
width = "100vw";
if (isNotNumber(width))
{
// the compiler knows that width here must be a string
if (width.endsWith('vw'))
{
// we have a 'width' such as 100vw
}
}
else
{
// the compiler is smart and knows width here must be number
var doubleWidth = width * 2;
}
typeguard 足够智能,可以将语句中的类型限制为 ONLY 。这允许编译器允许,如果类型是 ,则不允许 。width
if
string
width.endsWith(...)
string | number
你可以随心所欲地称呼 typeguard,,,但我认为它有点模棱两可且难以阅读。isNotNumber
isNumber
isString
isNotString
isString
评论
1..1
1,1
-32.1.12
undefined
NaN
undefined
NaN
undefined * 2
NaN
e
E
2E34
我最近写了一篇关于如何确保变量是有效数字的文章: https://github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md 这篇文章解释了如何确保浮点数或整数,如果这很重要的话( vs )。+x
~~x
本文假设变量以 a 或 a 开头,并且是可用/polyfilled。将其扩展到处理其他类型的内容也不难。这是它的精髓:string
number
trim
// Check for a valid float
if (x == null
|| ("" + x).trim() === ""
|| isNaN(+x)) {
return false; // not a float
}
// Check for a valid integer
if (x == null
|| ("" + x).trim() === ""
|| ~~x !== +x) {
return false; // not an integer
}
这个问题的公认答案有很多缺陷(正如其他几个用户所强调的那样)。这是在javascript中处理它的最简单和经过验证的方法之一:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
以下是一些很好的测试用例:
console.log(isNumeric(12345678912345678912)); // true
console.log(isNumeric('2 ')); // true
console.log(isNumeric('-32.2 ')); // true
console.log(isNumeric(-32.2)); // true
console.log(isNumeric(undefined)); // false
// the accepted answer fails at these tests:
console.log(isNumeric('')); // false
console.log(isNumeric(null)); // false
console.log(isNumeric([])); // false
评论
parseFloat
对于此应用程序来说是不够的,因为当它遇到第一个无法解析为数字的字符时,它将返回到目前为止解析的有效数字。例如。.parseFloat('1.1ea10') === 1.1
Number.isNaN
Number.isFinite
省去试图寻找“内置”解决方案的麻烦。
没有一个好的答案,这个线程中大量投票的答案是错误的。
npm install is-number
在 JavaScript 中,可靠地检查值是否为数字并不总是那么简单。开发人员通常使用 +、- 或 Number() 将字符串值转换为数字(例如,当从用户输入、正则表达式匹配、解析器等返回值时)。但是,有许多非直观的边缘情况会产生意想不到的结果:
console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+' '); //=> 0
console.log(typeof NaN); //=> 'number'
function isNumberCandidate(s) {
const str = (''+ s).trim();
if (str.length === 0) return false;
return !isNaN(+str);
}
console.log(isNumberCandidate('1')); // true
console.log(isNumberCandidate('a')); // false
console.log(isNumberCandidate('000')); // true
console.log(isNumberCandidate('1a')); // false
console.log(isNumberCandidate('1e')); // false
console.log(isNumberCandidate('1e-1')); // true
console.log(isNumberCandidate('123.3')); // true
console.log(isNumberCandidate('')); // false
console.log(isNumberCandidate(' ')); // false
console.log(isNumberCandidate(1)); // true
console.log(isNumberCandidate(0)); // true
console.log(isNumberCandidate(NaN)); // false
console.log(isNumberCandidate(undefined)); // false
console.log(isNumberCandidate(null)); // false
console.log(isNumberCandidate(-1)); // true
console.log(isNumberCandidate('-1')); // true
console.log(isNumberCandidate('-1.2')); // true
console.log(isNumberCandidate(0.0000001)); // true
console.log(isNumberCandidate('0.0000001')); // true
console.log(isNumberCandidate(Infinity)); // true
console.log(isNumberCandidate(-Infinity)); // true
console.log(isNumberCandidate('Infinity')); // true
if (isNumberCandidate(s)) {
// use +s as a number
+s ...
}
当防止空字符串和 null
// Base cases that are handled properly
Number.isNaN(Number('1')); // => false
Number.isNaN(Number('-1')); // => false
Number.isNaN(Number('1.1')); // => false
Number.isNaN(Number('-1.1')); // => false
Number.isNaN(Number('asdf')); // => true
Number.isNaN(Number(undefined)); // => true
// Special notation cases that are handled properly
Number.isNaN(Number('1e1')); // => false
Number.isNaN(Number('1e-1')); // => false
Number.isNaN(Number('-1e1')); // => false
Number.isNaN(Number('-1e-1')); // => false
Number.isNaN(Number('0b1')); // => false
Number.isNaN(Number('0o1')); // => false
Number.isNaN(Number('0xa')); // => false
// Edge cases that will FAIL if not guarded against
Number.isNaN(Number('')); // => false
Number.isNaN(Number(' ')); // => false
Number.isNaN(Number(null)); // => false
// Edge cases that are debatable
Number.isNaN(Number('-0b1')); // => true
Number.isNaN(Number('-0o1')); // => true
Number.isNaN(Number('-0xa')); // => true
Number.isNaN(Number('Infinity')); // => false
Number.isNaN(Number('INFINITY')); // => true
Number.isNaN(Number('-Infinity')); // => false
Number.isNaN(Number('-INFINITY')); // => true
当 NOT 防止空字符串和 null
时
用:parseInt
// Base cases that are handled properly
Number.isNaN(parseInt('1')); // => false
Number.isNaN(parseInt('-1')); // => false
Number.isNaN(parseInt('1.1')); // => false
Number.isNaN(parseInt('-1.1')); // => false
Number.isNaN(parseInt('asdf')); // => true
Number.isNaN(parseInt(undefined)); // => true
Number.isNaN(parseInt('')); // => true
Number.isNaN(parseInt(' ')); // => true
Number.isNaN(parseInt(null)); // => true
// Special notation cases that are handled properly
Number.isNaN(parseInt('1e1')); // => false
Number.isNaN(parseInt('1e-1')); // => false
Number.isNaN(parseInt('-1e1')); // => false
Number.isNaN(parseInt('-1e-1')); // => false
Number.isNaN(parseInt('0b1')); // => false
Number.isNaN(parseInt('0o1')); // => false
Number.isNaN(parseInt('0xa')); // => false
// Edge cases that are debatable
Number.isNaN(parseInt('-0b1')); // => false
Number.isNaN(parseInt('-0o1')); // => false
Number.isNaN(parseInt('-0xa')); // => false
Number.isNaN(parseInt('Infinity')); // => true
Number.isNaN(parseInt('INFINITY')); // => true
Number.isNaN(parseInt('-Infinity')); // => true
Number.isNaN(parseInt('-INFINITY')); // => true
用:parseFloat
// Base cases that are handled properly
Number.isNaN(parseFloat('1')); // => false
Number.isNaN(parseFloat('-1')); // => false
Number.isNaN(parseFloat('1.1')); // => false
Number.isNaN(parseFloat('-1.1')); // => false
Number.isNaN(parseFloat('asdf')); // => true
Number.isNaN(parseFloat(undefined)); // => true
Number.isNaN(parseFloat('')); // => true
Number.isNaN(parseFloat(' ')); // => true
Number.isNaN(parseFloat(null)); // => true
// Special notation cases that are handled properly
Number.isNaN(parseFloat('1e1')); // => false
Number.isNaN(parseFloat('1e-1')); // => false
Number.isNaN(parseFloat('-1e1')); // => false
Number.isNaN(parseFloat('-1e-1')); // => false
Number.isNaN(parseFloat('0b1')); // => false
Number.isNaN(parseFloat('0o1')); // => false
Number.isNaN(parseFloat('0xa')); // => false
// Edge cases that are debatable
Number.isNaN(parseFloat('-0b1')); // => false
Number.isNaN(parseFloat('-0o1')); // => false
Number.isNaN(parseFloat('-0xa')); // => false
Number.isNaN(parseFloat('Infinity')); // => false
Number.isNaN(parseFloat('INFINITY')); // => true
Number.isNaN(parseFloat('-Infinity')); // => false
Number.isNaN(parseFloat('-INFINITY')); // => true
笔记:
- 仅考虑字符串、空值和未初始化的值,以与解决原始问题保持一致。如果数组和对象是正在考虑的值,则存在其他边缘情况。
- 二进制、八进制、十六进制和指数表示法中的字符不区分大小写(即:“0xFF”、“0XFF”、“0xfF”等在上面所示的测试用例中都会产生相同的结果)。
- 与
Infinity
(区分大小写)不同,在某些情况下,作为测试用例以字符串格式传递给上述任何方法的Number
和Math
对象中的常量将被确定为不是数字。 - 有关如何将参数转换为
Number
以及为什么存在null
和空字符串的边缘情况的说明,请参阅此处。
评论
""
null
undefined
Infinity
"Infinity"
undefined
它对 TypeScript 无效,因为:
declare function isNaN(number: number): boolean;
对于 TypeScript,您可以使用:
/^\d+$/.test(key)
评论
/^\d+$/.test("-1") // false
要在 TS 中使用非数字,只需将值转换为 ,或者使用此处使用其他更全面的解决方案之一,这些解决方案使用 、 等。isNaN
any
Number
parseFloat
2019 年:包括 ES3、ES6 和 TypeScript 示例
也许这已经被重提了太多次了,但是我今天也和这个打过架,想发布我的答案,因为我没有看到任何其他答案可以如此简单或彻底地做到这一点:
ES3系列
var isNumeric = function(num){
return (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num);
}
DSW的
const isNumeric = (num) => (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num);
打字稿
const isNumeric = (num: any) => (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num as number);
这看起来很简单,涵盖了我在许多其他帖子中看到并自己想到的所有基础:
// Positive Cases
console.log(0, isNumeric(0) === true);
console.log(1, isNumeric(1) === true);
console.log(1234567890, isNumeric(1234567890) === true);
console.log('1234567890', isNumeric('1234567890') === true);
console.log('0', isNumeric('0') === true);
console.log('1', isNumeric('1') === true);
console.log('1.1', isNumeric('1.1') === true);
console.log('-1', isNumeric('-1') === true);
console.log('-1.2354', isNumeric('-1.2354') === true);
console.log('-1234567890', isNumeric('-1234567890') === true);
console.log(-1, isNumeric(-1) === true);
console.log(-32.1, isNumeric(-32.1) === true);
console.log('0x1', isNumeric('0x1') === true); // Valid number in hex
// Negative Cases
console.log(true, isNumeric(true) === false);
console.log(false, isNumeric(false) === false);
console.log('1..1', isNumeric('1..1') === false);
console.log('1,1', isNumeric('1,1') === false);
console.log('-32.1.12', isNumeric('-32.1.12') === false);
console.log('[blank]', isNumeric('') === false);
console.log('[spaces]', isNumeric(' ') === false);
console.log('null', isNumeric(null) === false);
console.log('undefined', isNumeric(undefined) === false);
console.log([], isNumeric([]) === false);
console.log('NaN', isNumeric(NaN) === false);
您还可以尝试自己的功能,并在这些用例中刚刚过去,并扫描所有用例的“true”。isNumeric
或者,要查看每个返回的值,请执行以下操作:
评论
isNumeric('3e2')
/ isNumeric(3e2)
2019年:实用而严格的数值有效性检查
通常,“有效数”是指不包括 NaN 和 Infinity 的 Javascript 数,即“有限数”。
要检查值的数值有效性(例如来自外部来源),您可以在 ESlint Airbnb 样式中定义:
/**
* Returns true if 'candidate' is a finite number or a string referring (not just 'including') a finite number
* To keep in mind:
* Number(true) = 1
* Number('') = 0
* Number(" 10 ") = 10
* !isNaN(true) = true
* parseFloat('10 a') = 10
*
* @param {?} candidate
* @return {boolean}
*/
function isReferringFiniteNumber(candidate) {
if (typeof (candidate) === 'number') return Number.isFinite(candidate);
if (typeof (candidate) === 'string') {
return (candidate.trim() !== '') && Number.isFinite(Number(candidate));
}
return false;
}
并按以下方式使用它:
if (isReferringFiniteNumber(theirValue)) {
myCheckedValue = Number(theirValue);
} else {
console.warn('The provided value doesn\'t refer to a finite number');
}
这是建立在前面的一些答案和评论之上的。它涵盖了所有边缘情况,还可以选择处理科学记数法:
const NUMBER_REG_EXP = /^-?\d+(?:\.\d+)?$/;
const SCIENTIFIC_NOTATION_REG_EXP = /^-?\d+(?:\.\d+)?(?:[eE]\d+)?$/;
const isNumeric = (n, allowScientificNotation = false) => (
(typeof n === 'number' && !Number.isNaN(n)) ||
(typeof n === 'string' && (allowScientificNotation ?
SCIENTIFIC_NOTATION_REG_EXP : NUMBER_REG_EXP).test(n))
);
这似乎抓住了看似无限数量的边缘情况:
function isNumber(x, noStr) {
/*
- Returns true if x is either a finite number type or a string containing only a number
- If empty string supplied, fall back to explicit false
- Pass true for noStr to return false when typeof x is "string", off by default
isNumber(); // false
isNumber([]); // false
isNumber([1]); // false
isNumber([1,2]); // false
isNumber(''); // false
isNumber(null); // false
isNumber({}); // false
isNumber(true); // false
isNumber('true'); // false
isNumber('false'); // false
isNumber('123asdf'); // false
isNumber('123.asdf'); // false
isNumber(undefined); // false
isNumber(Number.POSITIVE_INFINITY); // false
isNumber(Number.NEGATIVE_INFINITY); // false
isNumber('Infinity'); // false
isNumber('-Infinity'); // false
isNumber(Number.NaN); // false
isNumber(new Date('December 17, 1995 03:24:00')); // false
isNumber(0); // true
isNumber('0'); // true
isNumber(123); // true
isNumber(123.456); // true
isNumber(-123.456); // true
isNumber(-.123456); // true
isNumber('123'); // true
isNumber('123.456'); // true
isNumber('.123'); // true
isNumber(.123); // true
isNumber(Number.MAX_SAFE_INTEGER); // true
isNumber(Number.MAX_VALUE); // true
isNumber(Number.MIN_VALUE); // true
isNumber(new Number(123)); // true
*/
return (
(typeof x === 'number' || x instanceof Number || (!noStr && x && typeof x === 'string' && !isNaN(x))) &&
isFinite(x)
) || false;
};
因此,这将取决于您希望它处理的测试用例。
function isNumeric(number) {
return !isNaN(parseFloat(number)) && !isNaN(+number);
}
我一直在寻找的是 javascript 中的常规类型的数字。0, 1 , -1, 1.1 , -1.1 , 1E1 , -1E1 , 1e1 , -1e1, 0.1e10, -0.1.e10 , 0xAF1 , 0o172, Math.PI, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY
它们也是字符串的表示形式:
'0', '1', '-1', '1.1', '-1.1', '1E1', '-1E1', '1e1', '-1e1', '0.1e10', '-0.1.e10', '0xAF1', '0o172'
我确实想省略并且不将它们标记为数字'', ' ', [], {}, null, undefined, NaN
截至今天,所有其他答案似乎都未能通过其中一个测试用例。
评论
isNumeric('007')
true
TL的;博士
这很大程度上取决于您要解析为数字的内容。
内置函数之间的比较
由于没有一个现有的资源让我的灵魂满意,我试图弄清楚这些功能到底发生了什么。
这个问题的三个直接答案是这样的:
!isNaN(input)
(它给出的输出与+input === +input
)!isNaN(parseFloat(input))
isFinite(input)
但是,它们中的任何一个在每种情况下都是正确的吗?
我在几个案例中测试了这些函数,并以 markdown 的形式生成输出。这是它的样子:
input |
!isNaN(input) 或+input===+input |
!isNaN( parseFloat( input)) |
isFinite( input) |
评论 |
---|---|---|---|---|
123 | ✔️ | ✔️ | ✔️ | - |
'123' | ✔️ | ✔️ | ✔️ | - |
12.3 | ✔️ | ✔️ | ✔️ | - |
'12.3' | ✔️ | ✔️ | ✔️ | - |
' 12.3 ' | ✔️ | ✔️ | ✔️ | 空空格已修剪,如预期的那样。 |
1_000_000 | ✔️ | ✔️ | ✔️ | 数字分隔符理解,也是意料之中的。 |
'1_000_000' | ❌ | ✔️ | ❌ | 惊喜!JS 只是不会解析字符串中的数字分隔符。有关详细信息,请查看此问题。(为什么解析为浮点数有效?好吧,它没有。😉) |
'0b11111111' | ✔️ | ✔️ | ✔️ | 二进制形式理解了,因为它应该理解。 |
'0o377' | ✔️ | ✔️ | ✔️ | 八进制形式也理解。 |
“0xFF” | ✔️ | ✔️ | ✔️ | 当然,十六进制是可以理解的。有人不这么认为吗?😒 |
'' | ✔️ | ❌ | ✔️ | 空字符串应该是一个数字吗? |
' ' | ✔️ | ❌ | ✔️ | 仅空格字符串应该是一个数字吗? |
“ABC” | ❌ | ❌ | ❌ | 每个人都同意,而不是一个数字。 |
'12.34Ab!@#$' | ❌ | ✔️ | ❌ | 啊!现在,这是可以理解的。对我来说并不令人印象深刻,但在某些情况下可能会派上用场。parseFloat() |
'10e100' | ✔️ | ✔️ | ✔️ | 10100确实是一个数字。 但要小心!它比最大安全整数值 253(约 9×1015)大得多。有关详细信息,请阅读此内容。 |
'10e1000' | ✔️ | ✔️ | ❌ | 跟我说,救命! 虽然并不像看起来那么疯狂。在 JavaScript 中,大于 ~10308 的值四舍五入为无穷大,这就是原因。详情请看这里。 是的,将无穷大视为一个数字,并将无穷大解析为无穷大。 isNaN() parseFloat() |
零 | ✔️ | ❌ | ✔️ | 现在这很尴尬。在 JS 中,当需要转换时,null 变为零,我们得到一个有限数。 那为什么要在这里返回一个呢?有人请向我解释这个设计概念。 parseFloat(null) NaN |
定义 | ❌ | ❌ | ❌ | 不出所料。 |
无限 | ✔️ | ✔️ | ❌ | 如前所述,将无穷大视为一个数字,并将无穷大解析为无穷大。isNaN() parseFloat() |
所以。。。哪一个是“正确的”?
现在应该很清楚了,这在很大程度上取决于我们需要什么。例如,我们可能希望将 null 输入视为 0。在这种情况下,可以正常工作。isFinite()
同样,也许我们会从需要 10 100000000000 被视为有效数字时获得一点帮助(尽管问题仍然存在——为什么会这样,我们将如何处理)!isNaN()
当然,我们可以手动排除任何场景。
就像我的情况一样,我完全需要 的输出,除了 null 大小写、空字符串大小写和仅空格字符串大小写。此外,我对非常庞大的数字并不感到头疼。所以我的代码看起来像这样:isFinite()
/**
* My necessity was met by the following code.
*/
if (input === null) {
// Null input
} else if (input.trim() === '') {
// Empty or whitespace-only string
} else if (isFinite(input)) {
// Input is a number
} else {
// Not a number
}
而且,这是我生成表格的 JavaScript:
/**
* Note: JavaScript does not print numeric separator inside a number.
* In that single case, the markdown output was manually corrected.
* Also, the comments were manually added later, of course.
*/
let inputs = [
123, '123', 12.3, '12.3', ' 12.3 ',
1_000_000, '1_000_000',
'0b11111111', '0o377', '0xFF',
'', ' ',
'abc', '12.34Ab!@#$',
'10e100', '10e1000',
null, undefined, Infinity];
let markdownOutput = `| \`input\` | \`!isNaN(input)\` or <br>\`+input === +input\` | \`!isNaN(parseFloat(input))\` | \`isFinite(input)\` | Comment |
| :---: | :---: | :---: | :---: | :--- |\n`;
for (let input of inputs) {
let outputs = [];
outputs.push(!isNaN(input));
outputs.push(!isNaN(parseFloat(input)));
outputs.push(isFinite(input));
if (typeof input === 'string') {
// Output with quotations
console.log(`'${input}'`);
markdownOutput += `| '${input}'`;
} else {
// Output without quotes
console.log(input);
markdownOutput += `| ${input}`;
}
for (let output of outputs) {
console.log('\t' + output);
if (output === true) {
markdownOutput += ` | <div style="color:limegreen">true</div>`;
// markdownOutput += ` | ✔️`; // for stackoverflow
} else {
markdownOutput += ` | <div style="color:orangered">false</div>`;
// markdownOutput += ` | ❌`; // for stackoverflow
}
}
markdownOutput += ` ||\n`;
}
// Replace two or more whitespaces with $nbsp;
markdownOutput = markdownOutput.replaceAll(` `, ` `);
// Print markdown to console
console.log(markdownOutput);
评论
'0123'
一个字符串,它应该保持一个字符串,但这些技术中的任何一种都会检测到一个数字,并会导致丢失。0
这样它对我有用。
function isNumeric(num){
let value1 = num.toString();
let value2 = parseFloat(num).toString();
return (value1 === value2);
}
console.log(
isNumeric(123), //true
isNumeric(-123), //true
isNumeric('123'), //true
isNumeric('-123'), //true
isNumeric(12.2), //true
isNumeric(-12.2), //true
isNumeric('12.2'), //true
isNumeric('-12.2'), //true
isNumeric('a123'), //false
isNumeric('123a'), //false
isNumeric(' 123'), //false
isNumeric('123 '), //false
isNumeric('a12.2'), //false
isNumeric('12.2a'), //false
isNumeric(' 12.2'), //false
isNumeric('12.2 '), //false
)
有人也可能从基于正则表达式的答案中受益。在这里:
一个衬里是整数:
const isInteger = num => /^-?[0-9]+$/.test(num+'');
一个衬里是数字:接受整数和小数
const isNumeric = num => /^-?[0-9]+(?:\.[0-9]+)?$/.test(num+'');
评论
const isInteger = num => /^\s*-?[0-9]+\s*$/.test(num+'');
const isNumeric = num => /^\s*-?[0-9]+(?:\.[0-9]+)\s*?$/.test(num+'');
JavaScript 全局 isFinite(
) 检查值是否为有效(有限)数字。
参见 MDN 了解 Number.isFinite() 和全局 isFinite() 之间的区别。
let a = isFinite('abc') // false
let b = isFinite('123') // true
let c = isFinite('12a') // false
let d = isFinite(null) // true
console.log(a, b, c, d)
评论
上一个:参考 - 密码验证
评论
isNaN("")
isNaN(" ")
isNaN(false)
false