Question

Can anyone tell me the most efficient way to make a negative NSNumber positive?

Was it helpful?

Solution 2

Get the absolute value like that:

number = [NSNumber numberWithDouble:fabs([number doubleValue])];

OTHER TIPS

Doing this generically is surprisingly complex, because you need to find out the proper type of the number inside NSNumber.

Here is one way of doing it: add a category, and use a switch statement in the implementation to dispatch on the value of objCType

@interface NSNumber (AbsoluteValue)

-(NSNumber*)abs;

@end

@implementation NSNumber (AbsoluteValue)

-(NSNumber*)abs {
    switch (self.objCType[0]) {
        // Cases below cover only signed types
      case 'c': return [NSNumber numberWithChar:abs([self charValue])];
      case 's': return [NSNumber numberWithShort:abs([self shortValue])];
      case 'i': return [NSNumber numberWithInt:abs([self intValue])];
      case 'q': return [NSNumber numberWithLongLong:llabs([self longLongValue])];
      case 'f': return [NSNumber numberWithFloat:fabsf([self floatValue])];
      case 'd': return [NSNumber numberWithDouble:fabs([self doubleValue])];
      // Otherwise, the number is of an unsigned type, so it can be returned directly
      default: return self;
    }
}

@end

You can optimize this by returning self when the number is positive.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top