11

I am looking for a way to turn a NSDecimalNumber negative by multiplying by -1.

/* decNumber is the one I would like to turn negative */
NSDecimalNumber *decNumber = [values objectAtIndex:billIndex];

NSDecimalNumber *minusOne = [[NSDecimalNumber alloc] initWithInt: -1];
finalValue = [[NSDecimalNumber alloc] initWithDecimal: [[decNumber decimalNumberByMultiplyingBy: minusOne] decimalValue]];

This works but it feels like it's just too much for such a simple logic. Can you think of a better way to achieve this?

Macarse
  • 91,829
  • 44
  • 175
  • 230

3 Answers3

17

You could use NSDecimalNumber>>decimalNumberWithMantissa:exponent:isNegative to generate -1 more concisely.

/* Answers (aDecimal x -1) */
NSDecimalNumber* negate(NSDecimalNumber *aDecimal) {
    return [aDecimal decimalNumberByMultiplyingBy:
                    [NSDecimalNumber decimalNumberWithMantissa: 1
                                                      exponent: 0
                                                    isNegative: YES]];
}
D.Shawley
  • 58,213
  • 10
  • 98
  • 113
  • 3
    Why not just use `[NSDecimalNumber decimalNumberWithString:@"-1"]`? – ma11hew28 Dec 16 '11 at 20:58
  • @MattDiPasquale - that would work as well. It might not be as efficient, but creating new objects simply as temporaries isn't that efficient anyway. – D.Shawley Dec 16 '11 at 21:08
  • @DShawley, cool thanks. I think it's a bit more readable with the string method. But, I think the name of the method, `negate`, makes it clear anyway, so I'll go with your solution to be more efficient. Thanks! :) – ma11hew28 Dec 17 '11 at 15:10
  • For what its worth, i like the decimalNumberWithString by Matt. It does read easier. It might be less efficient but I like easy to read stuff. – oky_sabeni Apr 17 '13 at 02:34
3

Similar to the answer by D.Shawley, but extension and swift style.

extension NSDecimalNumber {
    /* Answers (aDecimal x -1) */
    func decimalNumberByNegating() -> NSDecimalNumber {
        return self.decimalNumberByMultiplyingBy(NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true));
    }
}
La-comadreja
  • 5,627
  • 11
  • 36
  • 64
Michał Dębski
  • 527
  • 4
  • 16
0

using bridge as

extension NSDecimalNumber {

    func decimalNumberByNegating() -> NSDecimalNumber {
        return -(self as Decimal) as NSDecimalNumber
    }
}
canius
  • 93
  • 5