Determine if NSNumber is NaN

Viewed 25280

How can I determine if a Cocoa NSNumber represents NaN (not a number)?

This emerges, for example, when I parse a string that has an invalid (non-numeric) contents.

9 Answers

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.

there is also the function isnan() i found it today.

There isn't really such an object for NSNumber since if it's not a number, then, well, it's not an NSNumber. It's more usual to use a nil object to represent this.

Related