0

How could I do it in Node.js to recognize if a string is a valid number?

Here are some examples of what I want:

"22"     => true
"- 22"   => true
"-22.23" => true
"22a"    => false
"2a2"    => false
"a22"    => false
"22 asd" => false

I dont actually need to return "true" or "false", but I need an unequivocally way to distinguish them. It seems like isNaN isnt available in node.js...

Enrique Moreno Tent
  • 24,127
  • 34
  • 104
  • 189

3 Answers3

0

I use the method suggested in this answer:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
Community
  • 1
  • 1
Raffaele
  • 20,627
  • 6
  • 47
  • 86
0

You can use regexp for example :

function is_number(n) {
   return (/^-?\d[0-9.e]*$/).test(n);
}
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
0

isNaN() is definitely available in node.js.

!isNaN(+n)

The unary plus operator is my personal choice; won't catch your "- 22" example, but you could use !isNaN(+n.replace(/\s/g, "") to strip spaces.

cjohn
  • 11,370
  • 3
  • 30
  • 17