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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With