tags:

views:

1266

answers:

3

I need to get the absolute value of an NSDecimalNumber without loss of precision. I can't seem to find a way to do this without converting to decimal or float (with a loss of precision). Is there a method to do this?

+7  A: 
Tim
I knew there had to be something simple I was missing. Thanks.
mreith
A: 

In my case I was using simple floats so the solution above seemed an overkill.

float someFloat = -0.035;

if(someFloat < 0)
    someFloat*=-1;
Sam V
A: 

There is a minor error in the answer: negativeOne should be a pointer. Here is a revised answer:

- (NSDecimalNumber *)abs:(NSDecimalNumber *)num {
    if [myNumber compare:[NSDecimalNumber zero]] == NSOrderedAscending) {
        // Number is negative. Multiply by -1
        NSDecimalNumber *negativeOne = [NSDecimalNumber decimalNumberWithMantissa:1
                                                                    exponent:0
                                                                  isNegative:YES];
        return [num decimalNumberByMultiplyingBy:negativeOne];
    } else {
        return num;
    }
}
Martin Stanley