tags:

views:

1158

answers:

5

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.

+5  A: 

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.

Adam Ernst
A: 

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.

Mike Abdullah
+1  A: 

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.

Ahruman
A: 

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

Johnny Mast
A: 

Any Boolean expression with NaN will always return false. But how is that useful?

I was getting Nan back from locationInView: while handling some gestures in an iPhone app. And was very pleased to find that any Boolean expression with NaN will always return false. I put this to use liek below:

//I was using the UIPanGestureRecognizer, and seems that on TouchUp I would get Nan for the /location .x - .y - pretty reasonible since in this case the end of a touch doesnt have a location. CGPoint location = [gestureRecognizer locationInView:self];

if ( location.x != location.x || location.y != location.y ) { return; }

So then as long .x and .y or legitimate float values, of course they will never be not equal to there own value. BUT in the case of .x or .y being NaN, the comparison will be false. And I can safely avoid computations with Nan.

Alan Morford