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?
Well, I'm using this one I made...
It's been working so far:
If you spot any problem with it, tell me, please.
Here's a one-liner to check if
sNum
is a valid numeric value; it has been tested for a wide variety of inputs:Try the isNan function:
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
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.In my application we are only allowing a-z A-Z and 0-9 characters. I found the answer above using " string % 1 === 0" worked unless the string began with 0xnn (like 0x10) and then it would return it as numeric when we didn't want it to. The following simple trap in my numeric check seems to do the trick in our specific cases.
Warning : This might be exploiting a longstanding bug in Javascript and Actionscript [Number("1" + the_string) % 1 === 0)], I can't speak for that, but it is exactly what we needed.
parseInt(), but be aware that this function is a bit different in the sense that it for example returns 100 for parseInt("100px").