Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if NSNumber is NaN

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.

like image 906
Adam Ernst Avatar asked Apr 05 '09 18:04

Adam Ernst


4 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.

like image 124
Adam Ernst Avatar answered Nov 14 '22 09:11

Adam Ernst


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.

like image 25
Jens Ayton Avatar answered Nov 14 '22 08:11

Jens Ayton


For decimals, at least:

[[NSDecimalNumber notANumber] isEqualToNumber:myNumber]
like image 15
Volokh Avatar answered Nov 14 '22 09:11

Volokh


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"
like image 12
Jakob Egger Avatar answered Nov 14 '22 10:11

Jakob Egger