Macarse
Macarse

Reputation: 93173

Turn a NSDecimalNumber negative

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?

Upvotes: 11

Views: 3170

Answers (3)

canius
canius

Reputation: 93

using bridge as

extension NSDecimalNumber {

    func decimalNumberByNegating() -> NSDecimalNumber {
        return -(self as Decimal) as NSDecimalNumber
    }
}

Upvotes: 0

Michał Dębski
Michał Dębski

Reputation: 537

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));
    }
}

Upvotes: 3

D.Shawley
D.Shawley

Reputation: 59633

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]];
}

Upvotes: 17

Related Questions