I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric()
function?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
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:
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:
My solution:
You can add additional conditions inside the loop, to fit you particular needs.
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.I do it like this:
Of course isString() will be tripped up here if you pass some other object that has 'length' defined.
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.