0

Possible Duplicate:
Is there a (built-in) way in JavaScript to check if a string is a valid number?

I am using JS in a riak map reduce job. I have a number I want to map and needs to be a number.

if I have a variable:

 var wp=sfggz5341&& or var=100

How can if test if number?

e.g.

if wp==Number:    
    OK 
else:    
    pass
Community
  • 1
  • 1
Tampa
  • 75,446
  • 119
  • 278
  • 425
  • possible duplicate of [Is there a (built-in) way in JavaScript to check if a string is a valid number?](http://stackoverflow.com/questions/175739/is-there-a-built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number), [Check whether variable is number or string in javascript](http://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript) – sachleen Jan 24 '13 at 06:48

5 Answers5

2

You can test using: if (!isNaN(+wp)). In other words, convert the 'may be number' to number (using the + operator. If it can't be converted, the result is NaN. So !isNaN(...) means it's a number.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
2

You can use the typeof operator (see MDN for details):

var wp = "sfggz53141";
if (typeof wp === "number") {
    // number here
} else if (typeof wp === "string") {
    // string here
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

You can either use isNaN() or isNumeric().

The isNumeric() can be used, but fails in following cases:

// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;

// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;

So the best way is:

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

Reference: https://stackoverflow.com/a/1830844/462627

Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
-1

You can use !NaN(wp) to check if the string is a number.

Blender
  • 289,723
  • 53
  • 439
  • 496
-1

try to use
isNaN()

This function returns true if the value is NaN, and false if not.

Dnyan Waychal
  • 1,418
  • 11
  • 27