How can I get the currency symbols for the corresponding currency code with Swift (macOS).
Example:
My code:
var formatter = NSNumberFormatter()
formatter.currencySymbol = getSymbol(currencyCode)
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
let number = NSNumber(double: (amount as NSString).doubleValue)
let amountWithSymbol = formatter.stringFromNumber(number)!
getSymbol(_ currencyCode: String) -> String
or.. is there a better way?
A bit late but this is a solution I used to get the $ instead of US$ etc. for currency symbol.
/*
* Bear in mind not every currency have a corresponding symbol.
*
* EXAMPLE TABLE
*
* currency code | Country & Currency | Currency Symbol
*
* BGN | Bulgarian lev | лв
* HRK | Croatian Kuna | kn
* CZK | Czech Koruna | Kč
* EUR | EU Euro | €
* USD | US Dollar | $
* GBP | British Pound | £
*/
func getSymbol(forCurrencyCode code: String) -> String? {
let locale = NSLocale(localeIdentifier: code)
return locale.displayNameForKey(NSLocaleCurrencySymbol, value: code)
}
Basically this creates NSLocale
from your currency code and grabs the display attribute for the currency. In cases where the result matches the currency code for example SEK
it will create new country specific locale by removing the last character from the currency code and appending "_en" to form SE_en
. Then it will try to get the currency symbol again.
Swift 3 & 4
func getSymbol(forCurrencyCode code: String) -> String? {
let locale = NSLocale(localeIdentifier: code)
if locale.displayName(forKey: .currencySymbol, value: code) == code {
let newlocale = NSLocale(localeIdentifier: code.dropLast() + "_en")
return newlocale.displayName(forKey: .currencySymbol, value: code)
}
return locale.displayName(forKey: .currencySymbol, value: code)
}