Search code examples
swiftcurrencynsnumberformatter

Dividing NumberFormatter .currency to convert a price into quarterly price


I have a NumberFormatter() with numberStyle as .currency. I am trying to convert this to a quarterly price by dividing it by 4.

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = product.priceLocale // product is a SKProduct object.

Attempting to divide by 4:

let quarter = NSDecimalNumber(value: 4)
let quarterly = formatter.string(from: product.price / quarter)

gives the error:

'NSDecimalNumber' is not implicitly convertible to 'Decimal'; did you mean to use 'as' to explicitly convert?

I also tried:

let quarterly = formatter.string(from: (product.price as Decimal) / quarter)

which gives the error:

Expression type 'NSDecimalNumber' is ambiguous without more context

How can I divide NumberFormatter.currency by 4?


Solution

  • Since product is an SKProduct then price is an NSDecimalNumber. That class provides the dividing method.

    let quarterly = formatter.string(from: product.price.dividing(by: quarter))