Determine if NSNumber is NaN

So, I found out that the class property [NSDecimalNumber notANumber] is just for this purpose. In some languages NaN != NaN, but this isn't the case in Cocoa.


As Mike Abdullah says, the natural way to represent a NaN in Cocoa is with nil, but [NSNumber numberWithDouble:NAN] does return a valid object. There is no NSNumber-specific way of detecting this, but the general way, isnan([foo doubleValue]), works. If you don’t like functions, you can stick it in a category.


For decimals, at least:

[[NSDecimalNumber notANumber] isEqualToNumber:myNumber]

To determine if NSNumber is a NaN, convert it to a double and use the C function isnan():

NSNumber *validNumber = [NSNumber numberWithDouble: 1.];
NSLog( @"%d", isnan(validNumber.doubleValue) ); // prints "0"

NSNumber *nanNumber = [NSNumber numberWithDouble: 0./0.];
NSLog( @"%d", isnan(nanNumber.doubleValue) ); // prints "1"

However, you should be careful, because there are other special values, for example:

NSNumber *posInfinity = [NSNumber numberWithDouble: 1./0.];
NSLog( @"%d", isnan(posInfinity.doubleValue) ); // prints "0"

If you want to check for these values as well, it's better to use isnormal() instead:

NSLog( @"%d", isnormal(validNumber.doubleValue) ); // prints "1"
NSLog( @"%d", isnormal(nanNumber.doubleValue) ); // prints "0"
NSLog( @"%d", isnormal(posInfinity.doubleValue) ); // prints "0"

I found that this works, but is it legal?

NSNumber *NaN = [NSDecimalNumber notANumber];

NSDecimalNumber *x = ... fill it somehow with NaN content ...

if ( x == NaN ) ... this works

is NaN guaranteeed to be a singleton constant value? Would be cool, but I suppose it is not, since all examples I found use the isEqual methods.