Question

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)
}
Was it helpful?

Solution

Compare with isNaN() function.

OTHER TIPS

Use isNaN() global function

if(isNaN(parseInt("test")))
{
   // do something 
}

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()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top