Inverting a negative NSNumber

Discussion in 'Mac Programming' started by mongrol, Jul 23, 2008.

  1. mongrol macrumors regular

    Joined:
    Jul 16, 2007
    #1
    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. :)
     
  2. italiano40 macrumors 65816

    italiano40

    Joined:
    Oct 7, 2007
    Location:
    NY
  3. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    NSNumber is a wrapper. You cannot perform arithmetic operations on it.
    Code:
    +(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
     
  4. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    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
     
  5. mongrol thread starter macrumors regular

    Joined:
    Jul 16, 2007
    #5
    Excellent. Thanks. Yes it is the absolute value I'm after.
     

Share This Page