swiftnsnumberformatter

NSNumberFormatter currency: "plusSign" replaces currency


When configuring an NSNumberFormatter in Swift the following:

extension NumberFormatter {
    convenience init(currencyCode code: String) {
        self.init()
        numberStyle = .currency
        locale = .autoupdatingCurrent
        maximumFractionDigits = 2
        positivePrefix = plusSign
        currencyCode = code
        minimumFractionDigits = 2
    }

it works for locales where the currency sign is at the end, e.g. de_DE: 12345 becomes +1.234,00 €. But for de_AT it becomes +1.234,00 - without the positivePrefix it would be € 1.234,00; how can I always show the sign in front (+ and -) but still keep the currency?

EDIT:

I would expect this test to fail (because the currency is missing), but it succeeds:

currencyFormatter.locale = Locale(identifier: "de_AT")
XCTAssertEqual(currencyFormatter.string(from: NSNumber(value: 0)), "+0,00")

Solution

  • Turns out accounting is your rescue, change the number style

    numberStyle = .currencyAccounting
    

    and you get your expected output