8

I have a var a;

Its value can be NaN, null and any +ve/-ve number including 0.

I require a condition which filters out all the values of a such that only >=0 values yield a true in if condition.

What is the best possible way to achieve this, I do not wish to use 3 different conditions joined using ||

Bhumi Singhal
  • 7,459
  • 9
  • 43
  • 69

7 Answers7

9
typeof x == "number" && x >= 0

This works as follows:

  • null -- typeof null == "object" so first part of expression returns false
  • NaN -- typeof NaN == "number" but NaN is not greater than, less than or equal to any number including itself so second part of expression returns false
  • number -- any other number greater than or equal to zero the expression returns true
Salman A
  • 229,425
  • 77
  • 398
  • 489
2

I had the same problem some weeks ago, I solved it with:

if(~~Number(test1)>0) {
  //...
}

http://jsfiddle.net/pT7pp/2/

RobSky
  • 307
  • 2
  • 6
1

This seems to work well:

if (parseFloat(x) === Math.sqrt(x*x))...

Test:

isPositive = function(x) { return parseFloat(x) === Math.sqrt(x*x) }
a = [null, +"xx", -100, 0, 100]
a.forEach(function(x) { console.log(x, isPositive(x))})
georg
  • 195,833
  • 46
  • 263
  • 351
1

NaN is not >= 0, so the only exclusion you need to make is for null:

if (a !== null && a >= 0) {
    ...
}
Alnitak
  • 313,276
  • 69
  • 379
  • 466
1

My best solution to filter those values out would be with 2 condition and it is like;

 if(a!=undefined && a>=0){
      console.log('My variable is filtered out.')
    }

I am not sure but there is no single condition usage to make it.

Ahmet DAL
  • 3,927
  • 6
  • 43
  • 66
1

Ohk ...But i actually found the ans .. it is so Simple .

parseInt(null) = NaN.

So if(parseInt(a)>=0){} would do ...Yayyee

Bhumi Singhal
  • 7,459
  • 9
  • 43
  • 69
0

Since you tagged jQuery, take a look at $.isNumeric()

if($.isNumeric(a) && a >= 0)
Shikiryu
  • 9,920
  • 6
  • 47
  • 74
  • Please don't use that! "$.isNumeric("-10"); // true" - that's never a good idea. – lqc May 10 '13 at 08:01
  • Since this function only do a basic `return !isNaN( parseFloat(obj) ) && isFinite( obj );`, I don't understand this statement. – Shikiryu May 10 '13 at 08:04
  • @lqc Plus, the OP statued that `a` could only be `NaN`, `null` or a `number`. – Shikiryu May 10 '13 at 08:05
  • So if you know it's a number, why feed it to a parseFloat() under the covers? Also, you throw away ``+Inf``, which is a valid positive number. – lqc May 10 '13 at 08:08
  • @lqc I didn't statuate that *this* is the best answer (I don't think it is) but just to give a jQuery alternative. `parseFloat` validate both Integer and Float (in this case) which are Numbers. But, fair enough for `+Inf` (still I doubt he'll use it ;)) – Shikiryu May 10 '13 at 08:11