Turn a NSDecimalNumber negative
Asked Answered
S

3

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?

Syntax answered 20/2, 2011 at 15:26 Comment(0)
T
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]];
}
Trivalent answered 20/2, 2011 at 16:12 Comment(4)
Why not just use [NSDecimalNumber decimalNumberWithString:@"-1"]?Benzvi
@MattDiPasquale - that would work as well. It might not be as efficient, but creating new objects simply as temporaries isn't that efficient anyway.Trivalent
@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! :)Benzvi
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.Terryn
Y
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));
    }
}
Yeoman answered 5/1, 2015 at 19:53 Comment(0)
F
0

using bridge as

extension NSDecimalNumber {

    func decimalNumberByNegating() -> NSDecimalNumber {
        return -(self as Decimal) as NSDecimalNumber
    }
}
Fleurdelis answered 10/12, 2020 at 9:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.