I\'m hoping there\'s something in the same conceptual space as the old VB6 IsNumeric()
function?
Well, I'm using this one I made...
It's been working so far:
function checkNumber(value) {
return value % 1 == 0;
}
If you spot any problem with it, tell me, please.
It is not valid for TypeScript as:
declare function isNaN(number: number): boolean;
For TypeScript you can use:
/^\d+$/.test(key)
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.
function isStringNumeric(str_input){
//concat a temporary 1 during the modulus to keep a beginning hex switch combination from messing us up
//very simple and as long as special characters (non a-z A-Z 0-9) are trapped it is fine
return '1'.concat(str_input) % 1 === 0;}
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.
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:
if(str === String(Number(str))) {
// it's a "perfectly formatted" number
}
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
and Number
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 initial Number
constructor) matches the original string.
This is built on some of the previous answers and comments. The following covers all the edge cases and fairly concise as well:
const isNumRegEx = /^-?(\d*\.)?\d+$/;
function isNumeric(n, allowScientificNotation = false) {
return allowScientificNotation ?
!Number.isNaN(parseFloat(n)) && Number.isFinite(n) :
isNumRegEx.test(n);
}
And you could go the RegExp-way:
var num = "987238";
if(num.match(/^-?\d+$/)){
//valid integer (positive or negative)
}else if(num.match(/^\d+\.\d+$/)){
//valid float
}else{
//not valid number
}