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...

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You are right. I dont know why it wasnt working before... thanks!
No problem. It should be noted that javascript thinks +"" and +[] are 0. So this solution doesn't hold up under the very best garbage you throw at it.
0

I use the method suggested in this answer:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

1 Comment

isNaN is not available in nodejs
0

You can use regexp for example :

function is_number(n) {
   return (/^-?\d[0-9.e]*$/).test(n);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.