Aamir Aamir - 13 days ago 7
iOS Question

iOS format price in different currencies

I am working with Swift 2.0 (xcode 7.2, iOS 9).
I need to display prices for different currencies in different formats, I tried googling and spent many hours with not luck yet.

This is how my current Swift code stands

var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.locale = NSLocale.currentLocale()
formatter.stringFromNumber(4500000)
//Output : $4,500,000.00
//Expected : 4,500,000 Руб.


I am unable to change the grouping separator, currency symbol and position of the currency symbol.

Thank you all in advance.

Answer

I ended up with following class:

class Currency {
    var currencyFormatter = NumberFormatter()
    var currencySymbol: String
    var isRTL: Bool

    init(_ currencySymbol: String, minFractionDigits: Int, maxFractionDigits: Int, isRTL: Bool) {
        self.currencyFormatter.currencySymbol = ""
        self.currencyFormatter.minimumFractionDigits = minFractionDigits
        self.currencyFormatter.maximumFractionDigits = maxFractionDigits
        self.currencyFormatter.numberStyle = .currency

        self.currencySymbol = currencySymbol
        self.isRTL = isRTL
    }

    func beautify(price: Double) -> String {
        let str = self.currencyFormatter.string(from: NSNumber(value: price))!
        if self.isRTL {
            return str + self.currencySymbol
        }
        return self.currencySymbol + str
    }

    static func format(price: Double, currencyCode: String) -> String {
        switch (currencyCode) {
        case "BYR":
            return CurrencyFormatters.byrFormat.beautify(price: price)
        case "EUR":
            return CurrencyFormatters.eurFormat.beautify(price: price)
        case "RUB":
            return CurrencyFormatters.rubFormat.beautify(price: price)
        default:
            return CurrencyFormatters.usdFormat.beautify(price: price)
        }
    }
}

Initialize your desired formatters

struct CurrencyFormatters {
    static let byrFormat = Currency(" Руб.", minFractionDigits: 2, maxFractionDigits: 2, isRTL: true)
    static let usdFormat = Currency("US $", minFractionDigits: 2, maxFractionDigits: 2, isRTL: false)
    static let eurFormat = Currency("€ ", minFractionDigits: 2, maxFractionDigits: 2, isRTL: false)
    static let rubFormat = Currency("\u{20BD} ", minFractionDigits: 0, maxFractionDigits: 1, isRTL: false)
}

Usage

Currency.format(price: 12345.67, currencyCode: "USD")