Search code examples
swiftios8nsnumberformatternsdecimalnumber

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.


Solution

  • 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()