user4732515
user4732515

Reputation:

Convert NSDecimalNumbers to Negative

Working on a budget app in swift.

Essentially, there is a label that displays keypad textInput to currencyStyle and displays this number ($5.00), then waits for user to choose Debit or Withdraw. If debit, number is appended to Table, but I'm lost when it comes to Withdraw(-).

I would like to

  1. Convert NSDecimalNumber which is formatted as currency to a negative for appending to a tableView: String ($5.00 to -$5.00).

  2. Convert NSDecimalNumber value to a negative and add to an NSNumber array that is storing numbers to be calculated for an available balance (5.50 to -5.50)

For both I have tried using NSNumberFormatter negativePrefix and a few other properties in Apple Documentation to no avail. Even tried creating a negative NSNumber value = -100.0, but app crashed during division.

Any help would be appreciated.

Upvotes: 2

Views: 2973

Answers (3)

Leo Dabus
Leo Dabus

Reputation: 236260

You can also subtract its own value from zero and return it as follow:

extension NSDecimalNumber {
    var negative: NSDecimalNumber { NSDecimalNumber.zero.subtracting(self) }
}

NSDecimalNumber(value: 15.6).negative  // -15.6

Upvotes: 2

ABakerSmith
ABakerSmith

Reputation: 22939

You could override the - operator. For example:

prefix func -(number: NSDecimalNumber) -> NSDecimalNumber {
    return number.decimalNumberByMultiplyingBy(NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true))
}

You can then use this like so:

let number = NSDecimalNumber(double: 5.00)
let negativeNumber = -number

Upvotes: 2

aksh1t
aksh1t

Reputation: 5448

To easily negate the NSDecimalNumber create an extension in Swift like this:

extension NSDecimalNumber {
    func negative() -> NSDecimalNumber {
        return self.decimalNumberByMultiplyingBy(NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true));
    }
}

You can then just negate your NSDecimalNumber like this:

yourNumber = yourNumber.negative() 

Upvotes: 3

Related Questions