PDA

View Full Version : Inverting a negative NSNumber




mongrol
Jul 23, 2008, 06:18 PM
Can anyone tell me the most efficient way to make a negative NSNumber positive?

If I have -1.5 I want to cheaply make it 1.5. Also If I feed 1.5 into the same function I still want 1.5

Cheating by subtracting the same number twice is not what I'm looking for. :)



italiano40
Jul 23, 2008, 06:20 PM
number*-1

lee1210
Jul 23, 2008, 06:25 PM
NSNumber is a wrapper. You cannot perform arithmetic operations on it.

+(NSNumber *)absoluteValue:(NSNumber *)input {
return [NSNumber numberWithDouble:fabs([input doubleValue])];
}


I don't know the "type" you initialized your input with, so you may want to adjust to numberWithFloat, etc. instead.

You will need to include/import math.h for fabs or fabsf.

-Lee

lee1210
Jul 23, 2008, 06:26 PM
number*-1

I think the OP is looking for the absolute value, not just a way to get a negative from a positive and vice-versa.

-Lee

mongrol
Jul 23, 2008, 07:14 PM
Excellent. Thanks. Yes it is the absolute value I'm after.