如何检查字符串是否是有效数字?
我希望有一些东西与旧的 VB6 IsNumeric()
函数处于相同的概念空间中?
I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric()
function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
2020 年 10 月 2 日:请注意,许多简单的方法都充满了微妙的错误(例如空格、隐式部分解析、基数、数组强制转换等),这里的许多答案都未能考虑到这些错误帐户。 以下实现可能适合您,但请注意,它不支持除小数点“
.
”之外的数字分隔符:要检查变量(包括字符串)是否为数字,请检查是否它不是数字:
无论变量内容是字符串还是数字,这都有效。
示例
当然,如果需要,您可以否定这一点。 例如,要实现您给出的
IsNumeric
示例:将包含数字的字符串转换为数字:
仅当字符串 only 包含数字字符时才有效,否则返回 <代码>NaN。
示例
将字符串松散地转换为数字
对于将 '12px' 转换为 12 很有用,例如:
示例
浮点数
请记住,与
+num
不同,parseInt
(作为顾名思义)将通过去掉小数点后面的所有内容将浮点数转换为整数(如果您想使用parseInt()
因为这种行为,您可能最好使用另一种方法):空字符串
空字符串可能有点违反直觉。
+num
将空字符串或带空格的字符串转换为零,并且isNaN()
假设相同:但
parseInt()
不同意:2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point "
.
":To check if a variable (including a string) is a number, check if it is not a number:
This works regardless of whether the variable content is a string or number.
Examples
Of course, you can negate this if you need to. For example, to implement the
IsNumeric
example you gave:To convert a string containing a number into a number:
Only works if the string only contains numeric characters, else it returns
NaN
.Examples
To convert a string loosely to a number
Useful for converting '12px' to 12, for example:
Examples
Floats
Bear in mind that, unlike
+num
,parseInt
(as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to useparseInt()
because of this behaviour, you're probably better off using another method instead):Empty strings
Empty strings may be a little counter-intuitive.
+num
converts empty strings or strings with spaces to zero, andisNaN()
assumes the same:But
parseInt()
does not agree:如果您只是想检查字符串是否是整数(没有小数位),则正则表达式是一个好方法。 其他方法(例如
isNaN
)对于如此简单的事情来说太复杂了。要仅允许正整数,请使用以下命令:
If you're just trying to check if a string is a whole number (no decimal places), regex is a good way to go. Other methods such as
isNaN
are too complicated for something so simple.To only allow positive whole numbers use this:
这个问题的公认答案有很多缺陷(正如其他几个用户所强调的那样)。 这是最简单的方法之一。 在 javascript 中行之有效的方法:
以下是一些很好的测试用例:
The accepted answer for this question has quite a few flaws (as highlighted by couple of other users). This is one of the easiest & proven way to approach it in javascript:
Below are some good test cases:
你可以采用 RegExp 方式:
And you could go the RegExp-way:
如果您确实想确保字符串仅包含数字、任何数字(整数或浮点数)以及确切的数字,则不能使用
parseInt()
/parseFloat()
、Number()
或!isNaN()
本身。 请注意,当Number()
返回数字时,!isNaN()
实际上返回true
,而当Number()
返回数字时,则返回false
它将返回 NaN,因此我将把它排除在其余讨论之外。parseFloat()
的问题是,如果字符串包含任何数字,即使该字符串不包含 only 且完全,它也会返回一个数字em> 数字:Number()
的问题是,如果传递的值根本不是数字,它将返回一个数字!滚动你自己的正则表达式的问题是,除非你创建精确的正则表达式来匹配 Javascript 识别的浮点数,否则你将错过一些情况或识别出不应该的情况。 即使您可以推出自己的正则表达式,为什么呢? 有更简单的内置方法可以做到这一点。
然而,事实证明,对于
parseFloat()
返回数字的每种情况,Number()
(和isNaN()
)都做了正确的事情当不应该的时候,反之亦然。 因此,要查明一个字符串是否确实是一个数字,请调用这两个函数并查看它们是否都返回 true:If you really want to make sure that a string contains only a number, any number (integer or floating point), and exactly a number, you cannot use
parseInt()
/parseFloat()
,Number()
, or!isNaN()
by themselves. Note that!isNaN()
is actually returningtrue
whenNumber()
would return a number, andfalse
when it would returnNaN
, so I will exclude it from the rest of the discussion.The problem with
parseFloat()
is that it will return a number if the string contains any number, even if the string doesn't contain only and exactly a number:The problem with
Number()
is that it will return a number in cases where the passed value is not a number at all!The problem with rolling your own regex is that unless you create the exact regex for matching a floating point number as Javascript recognizes it you are going to miss cases or recognize cases where you shouldn't. And even if you can roll your own regex, why? There are simpler built-in ways to do it.
However, it turns out that
Number()
(andisNaN()
) does the right thing for every case whereparseFloat()
returns a number when it shouldn't, and vice versa. So to find out if a string is really exactly and only a number, call both functions and see if they both return true:2019:包括 ES3、ES6 和 TypeScript 示例
也许这已经被重复了太多次,但是我今天也与这个问题作斗争,并想发布我的答案,因为我没有看到任何其他答案可以如此简单或彻底地做到这一点:
ES3
ES6
Typescript
这看起来很简单,涵盖了我在许多其他帖子中看到并自己想到的所有基础:
您也可以尝试自己的
isNumeric
函数,然后在这些用例中过去并扫描“对他们所有人来说都是如此。或者,要查看每个返回的值:
2019: Including ES3, ES6 and TypeScript Examples
Maybe this has been rehashed too many times, however I fought with this one today too and wanted to post my answer, as I didn't see any other answer that does it as simply or thoroughly:
ES3
ES6
Typescript
This seems quite simple and covers all the bases I saw on the many other posts and thought up myself:
You can also try your own
isNumeric
function and just past in these use cases and scan for "true" for all of them.Or, to see the values that each return:
TL;DR
这很大程度上取决于您想要将什么解析为数字。
内置函数之间的比较
由于现有的资源都不能满足我的需求,我试图弄清楚这些函数到底发生了什么。
这个问题的三个直接答案感觉就像:
!isNaN(input)
(它提供与+input === +input
相同的输出)!isNaN(parseFloat (input))
isFinite(input)
但是它们中的任何一个在每种场景中都是正确的吗?
我在几种情况下测试了这些函数,并以降价形式生成输出。 它看起来像这样:
input
!isNaN(input)
或+input===+input
!isNaN (
parseFloat(
输入))
isFinite(
输入)
TL;DR
It depends largely on what you want to parse as a number.
Comparison Between Built-in Functions
As none of the existing sources satisfied my soul, I tried to figure out what actually was happening with these functions.
Three immediate answers to this question felt like:
!isNaN(input)
(which gives the same output as+input === +input
)!isNaN(parseFloat(input))
isFinite(input)
But are any of them correct in every scenario?
I tested these functions in several cases, and generated output as markdown. This is what it looks like:
input
!isNaN(input)
or+input===+input
!isNaN(
parseFloat(
input))
isFinite(
input)
parseFloat()
does. Not impressive to me, but may come handy in certain cases.But caution! It's way more larger than the maximum safe integer value 253 (about 9×1015). Read this for details.
Though not as crazy as it may seem. In JavaScript, a value larger than ~10308 is rounded to infinity, that's why. Look here for details.
And yes,
isNaN()
considers infinity as a number, andparseFloat()
parses infinity as infinity.Then why
parseFloat(null)
should return aNaN
here? Someone please explain this design concept to me.isNaN()
considers infinity as a number, andparseFloat()
parses infinity as infinity.So...which of them is "correct"?
Should be clear by now, it depends largely on what we need. For example, we may want to consider a null input as 0. In that case
isFinite()
will work fine.Again, perhaps we will take a little help from
isNaN()
when 1010000000000 is needed to be considered a valid number (although the question remains—why would it be, and how would we handle that)!Of course, we can manually exclude any of the scenarios.
Like in my case, I needed exactly the outputs of
isFinite()
, except for the null case, the empty string case, and the whitespace-only string case. Also I had no headache about really huge numbers. So my code looked like this:And also, this was my JavaScript to generate the table:
尝试使用 isNan 函数:
Try the isNan function:
JavaScript 全局
isFinite()
检查值是否是有效(有限)数字。
请参阅 MDN,了解 Number 之间的差异.isFinite() 和全局 isFinite()。
The JavaScript global
isFinite()
checks if a value is a valid (finite) number.See MDN for the difference between Number.isFinite() and global isFinite().
老问题,但给出的答案中缺少几点。
科学记数法。
!isNaN('1e+30')
为true
,但是在大多数情况下,当人们询问数字时,他们会这样做不想匹配像1e+30
这样的东西。大浮点数可能表现得很奇怪
观察(使用 Node.js):
另一方面:
因此,如果期望
String(Number(s)) === s
,那么最好将字符串限制为最多 15 位(省略前导零后)。Infinity
鉴于此,检查给定字符串是否是满足以下所有条件的数字:
Number
并返回String
并不是一件容易的事。 这是一个简单的版本:
然而,即使这个版本也远未完成。 这里不处理前导零,但它们确实会影响长度测试。
Old question, but there are several points missing in the given answers.
Scientific notation.
!isNaN('1e+30')
istrue
, however in most of the cases when people ask for numbers, they do not want to match things like1e+30
.Large floating numbers may behave weird
Observe (using Node.js):
On the other hand:
So, if one expects
String(Number(s)) === s
, then better limit your strings to 15 digits at most (after omitting leading zeros).Infinity
Given all that, checking that the given string is a number satisfying all of the following:
Number
and back toString
is not such an easy task. Here is a simple version:
However, even this one is far from complete. Leading zeros are not handled here, but they do screw the length test.
有人也可能从基于正则表达式的答案中受益。 如下:
Oneliner isInteger:
Oneliner isNumeric: 接受整数和小数
Someone may also benefit from a regex based answer. Here it is:
One liner isInteger:
One liner isNumeric: Accepts integers and decimals
我已经测试过,迈克尔的解决方案是最好的。 为他上面的答案投票(在本页搜索“如果你真的想确保一个字符串”来找到它)。 本质上,他的答案是这样的:
它适用于每个测试用例,我在这里记录了:
https://jsfiddle.net/wggehvp9/5/
对于这些边缘情况,许多其他解决方案都失败了:
' '、null、“”、true 和 []。
理论上,您可以通过适当的错误处理来使用它们,例如:
或者
对
/\s/, null, "", true, false, [] (还有其他?)
I have tested and Michael's solution is best. Vote for his answer above (search this page for "If you really want to make sure that a string" to find it). In essence, his answer is this:
It works for every test case, which I documented here:
https://jsfiddle.net/wggehvp9/5/
Many of the other solutions fail for these edge cases:
' ', null, "", true, and [].
In theory, you could use them, with proper error handling, for example:
or
with special handling for
/\s/, null, "", true, false, [] (and others?)
您可以在传递时使用 Number 的结果其构造函数的参数。
如果参数(字符串)无法转换为数字,则返回 NaN,因此您可以确定提供的字符串是否为有效数字。
注意:注意当传递空字符串或
'\t\t'
和'\n\t'
作为Number时将返回0; 传递 true 将返回 1,传递 false 将返回 0。You can use the result of Number when passing an argument to its constructor.
If the argument (a string) cannot be converted into a number, it returns NaN, so you can determinate if the string provided was a valid number or not.
Notes: Note when passing empty string or
'\t\t'
and'\n\t'
as Number will return 0; Passing true will return 1 and false returns 0.也许有一两个人遇到这个问题,需要比平时更严格检查(就像我一样)。 在这种情况下,这可能会有用:
小心! 这将拒绝
.1
、40.000
、080
、00.1
等字符串。 它非常挑剔 - 字符串必须与数字的“最小完美形式”匹配才能通过此测试。它使用
String
和Number
构造函数将字符串转换为数字并再次转换回来,从而检查 JavaScript 引擎的“完美最小形式”(它转换为的形式)是否与初始Number
构造函数)匹配原始字符串。Maybe there are one or two people coming across this question who need a much stricter check than usual (like I did). In that case, this might be useful:
Beware! This will reject strings like
.1
,40.000
,080
,00.1
. It's very picky - the string must match the "most minimal perfect form" of the number for this test to pass.It uses the
String
andNumber
constructor to cast the string to a number and back again and thus checks if the JavaScript engine's "perfect minimal form" (the one it got converted to with the initialNumber
constructor) matches the original string.我喜欢这种简单性。
上面是常规的 Javascript,但我将其与打字稿结合使用 typeguard< /a> 用于智能类型检查。 这对于打字稿编译器非常有用,可以为您提供正确的智能感知,并且没有类型错误。
Typescript typeguards
警告:请参阅下面 Jeremy 的评论。这对某些值有一些问题,我现在没有时间修复它,但是使用 typescript typeguard 的想法很有用,所以我不会删除此部分。
假设您有一个属性
width
,它是number | 字符串
。 您可能想要根据它是否是字符串来执行逻辑。typeguard 足够智能,可以将
if
语句中的width
类型限制为仅string
。 这允许编译器允许width.endsWith(...)
,如果类型是string | 则不允许。 号码。
您可以将 typeguard 称为任何您想要的
isNotNumber
、isNumber
、isString
、isNotString
但我认为isString
有点含糊并且难以阅读。I like the simplicity of this.
The above is regular Javascript, but I'm using this in conjunction with a typescript typeguard for smart type checking. This is very useful for the typescript compiler to give you correct intellisense, and no type errors.
Typescript typeguards
Warning: See Jeremy's comment below. This has some issues with certain values and I don't have time to fix it now, but the idea of using a typescript typeguard is useful so I won't delete this section.
Let's say you have a property
width
which isnumber | string
. You may want to do logic based on whether or not it's a string.The typeguard is smart enough to constrain the type of
width
within theif
statement to be ONLYstring
. This permits the compiler to allowwidth.endsWith(...)
which it wouldn't allow if the type wasstring | number
.You can call the typeguard whatever you want
isNotNumber
,isNumber
,isString
,isNotString
but I thinkisString
is kind of ambiguous and harder to read.为什么 jQuery 的实现不够好?
迈克尔提出了类似的建议(尽管我在这里窃取了“user1691651 - John”的修改版本):
以下是一个很可能性能不佳但结果可靠的解决方案。 这是一个由 jQuery 1.12.4 实现和 Michael 的答案制成的装置,对前导/尾随空格进行了额外检查(因为 Michael 的版本对于带有前导/尾随空格的数字返回 true):
不过,后一个版本有两个新变量。 人们可以通过以下方式绕过其中之一:
我还没有对其中任何一个进行太多测试,除了手动测试我将在当前困境中遇到的少数用例之外,其他方式都是非常标准的东西。 这是一种“站在巨人肩膀上”的局面。
Why is jQuery's implementation not good enough?
Michael suggested something like this (although I've stolen "user1691651 - John"'s altered version here):
The following is a solution with most likely bad performance, but solid results. It is a contraption made from the jQuery 1.12.4 implementation and Michael's answer, with an extra check for leading/trailing spaces (because Michael's version returns true for numerics with leading/trailing spaces):
The latter version has two new variables, though. One could get around one of those, by doing:
I haven't tested any of these very much, by other means than manually testing the few use-cases I'll be hitting with my current predicament, which is all very standard stuff. This is a "standing-on-the-shoulders-of-giants" situation.
2019:实用且严格的数字有效性检查
通常,“有效数字”是指不包括 NaN 和 Infinity 的 Javascript 数字,即“有限数字”。
要检查值的数字有效性(例如来自外部源),您可以在 ESlint Airbnb 样式中定义:
并以这种方式使用它:
2019: Practical and tight numerical validity check
Often, a 'valid number' means a Javascript number excluding NaN and Infinity, ie a 'finite number'.
To check the numerical validity of a value (from an external source for example), you can define in ESlint Airbnb style :
and use it this way:
它对于 TypeScript 无效,如下所示:
declare function isNaN(number: number): boolean;
对于 TypeScript,您可以使用:
/^\d+$/.test(key)
It is not valid for TypeScript as:
declare function isNaN(number: number): boolean;
For TypeScript you can use:
/^\d+$/.test(key)
parseInt(),但请注意该函数有点不同,例如它为 parseInt("100px") 返回 100。
parseInt(), but be aware that this function is a bit different in the sense that it for example returns 100 for parseInt("100px").
引用:
如果您需要检查前导/尾随空格,则不完全为 true - 例如,当需要一定数量的数字时,您需要获取,例如、“1111”,而不是“111”或“111”,可能是 PIN 输入。
更好地使用:
Quote:
is not entirely true if you need to check for leading/trailing spaces - for example when a certain quantity of digits is required, and you need to get, say, '1111' and not ' 111' or '111 ' for perhaps a PIN input.
Better to use:
当防范空字符串和
null
时当不防范空字符串和
null
时使用
parseInt:
使用
parseFloat
:注释:
Infinity
(区分大小写)不同,在某些情况下,Number 中的常量以字符串格式作为测试用例传递给上述任何方法的
和Math
对象将被确定为不是数字。Number
以及为什么存在null
和空字符串的边缘情况。When guarding against empty strings and
null
When NOT guarding against empty strings and
null
Using
parseInt
:Using
parseFloat
:Notes:
Infinity
(case-sensitive) in some cases, constants from theNumber
andMath
objects passed as test cases in string format to any of the methods above will be determined to not be numbers.Number
and why the edge cases fornull
and empty strings exist.这样对我有用。
This way it works for me.
这是一个相当老的问题,但第一个出现的问题是谷歌搜索,通读答案后发现有很多混乱,而且 Node 在处理数字时非常混乱......
很多答案都很好,对于大多数情况来说可能已经足够好了,但我试图利用所有的“陷阱”并提出一个“安全”的解决方案来覆盖所有指出的区域,以及我想出的(不是那么简单的)解决方案是:
这适用于我在此线程中找到的大多数情况:
编辑:当我们决定开始在我们公司的全球范围内使用它时,我将其作为
npm
包发布给任何感兴趣的人:This is a fairly old question, but the first that turns up Googling, and having read through the answers there is a lot of confusion, and Node is very confusing when it comes to handling numbers...
A lot of the answers are good, and probably good enough for most cases, but I tried to leverage all of the "pit falls" and come up with a "safe" solution that would cover all the pointed out areas, and the (not so simple) solution I came up with is:
This will work with most cases I found in this thread:
EDIT: As we decided to start using this globally in our company, I published it as an
npm
package for anyone interested:这是建立在之前的一些答案和评论的基础上的。 它涵盖了所有边缘情况,还可以选择处理科学记数法:
This is built on some of the previous answers and comments. It covers all the edge cases and also handles scientific notation optionally:
如果有人陷入如此困境,我花了一些时间尝试修补 moment.js (https:// github.com/moment/moment)。 这是我从中得到的一些东西:
处理以下情况:
正确! :
错误的! :
讽刺的是,这是我最困扰的一个:
欢迎任何建议。 :]
If anyone ever gets this far down, I spent some time hacking on this trying to patch moment.js (https://github.com/moment/moment). Here's something that I took away from it:
Handles the following cases:
True! :
False! :
Ironically, the one I am struggling with the most:
Any suggestions welcome. :]
我最近写了一篇关于如何确保变量是有效数字的文章: https://github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md 本文解释了如何确保浮点或整数(如果这很重要)(
+x
与~~x
)。本文假设变量首先是一个字符串或数字,并且修剪可用/填充。 扩展它来处理其他类型也不难。 这是它的核心内容:
I recently wrote an article about ways to ensure a variable is a valid number: https://github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md The article explains how to ensure floating point or integer, if that's important (
+x
vs~~x
).The article assumes the variable is a
string
or anumber
to begin with andtrim
is available/polyfilled. It wouldn't be hard to extend it to handle other types, as well. Here's the meat of it:省去尝试寻找“内置”解决方案的麻烦。
没有一个好的答案,并且该线程中获得大力支持的答案是错误的。
npm install is-number
Save yourself the headache of trying to find a "built-in" solution.
There isn't a good answer, and the hugely upvoted answer in this thread is wrong.
npm install is-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
截至今天,所有其他答案似乎都未能通过这些测试用例之一。
So, it will depend on the test cases that you want it to handle.
What I was looking for was regular types of numbers in 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
And also they're representations as strings:
'0', '1', '-1', '1.1', '-1.1', '1E1', '-1E1', '1e1', '-1e1', '0.1e10', '-0.1.e10', '0xAF1', '0o172'
I did want to leave out and not mark them as numeric
'', ' ', [], {}, null, undefined, NaN
As of today, all other answers seemed to failed one of these test cases.
您还可以使用简单的 parseInt 函数...以及 if 条件
例如
You can also use a simple parseInt function too... with an if the condition
for example