views:

90

answers:

3

The AS3 documentation states that if you pass in a string to parseInt that is not a number it will return NaN. However, when I try to compare to NaN the compiler gives me the following error:

Warning: 1098: Illogical comparison with NaN. This statement always evaluates to false.

The statement is actually true. Comparing to NaN will always return false. How can I compare to NaN to detect if what was parsed was NaN?

if( parseInt("test") == NaN )
{
   // do something (never gets here)
}
+2  A: 

Use isNaN() global function

if(isNaN(parseInt("test")))
{
   // do something 
}
Amarghosh
+3  A: 

Compare with isNaN() function.

alxx
Slap forehead. Of course. I now remember I had the same problem in AS2 years ago. Why isn't the parseInt documentation referring to the isNaN function?
Luke
+1  A: 

Everyone is correct, use the isNaN() function:

http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/package.html#isNaN()

I've never really liked this method. I prefer to test for positives.

Interestingly though, if a Number is NaN then it will not equate to itself:

var parsed_int:Number = parseInt("test");
if(parsed_int != parsed_int)
  trace("NaN");

Therefor, testing if the Number equates to itself should give you the positive:

var parsed_int:Number = parseInt("123");
if(parsed_int == parsed_int)
  trace("Number");

It's not very clear what your intentions are when reading the code, so be sure to comment it if you use it.

Or you could add a top-level function:

function isNumber(num:Number):Boolean{
  return num == num;
}

And a note for the optimisation nuts out there. The inline version is fastest.

Just for reference: http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/package.html#parseInt()

Joony
The `isNaN` function is self-documenting however. Without a comment explaining why you are comparing a value against itself it just looks like a redundant piece of code.
Sly_cardinal
Yes, but I always find it interesting to know how something works. Plus if you're looking to only do something if parseInt returns a Number the you end up with code like if(!isNaN(parseInt("test"))). Is not not a number? It's just ugly in my opinion.
Joony