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?
The getSymbol() method is used to get the symbol of a given currency for the default DISPLAY locale. For example, for the US Dollar, the symbol is "$" if the default locale is the US, while for other locales it may be "US$". If no symbol can be determined, the ISO 4217 currency code is returned.
123 key in the lower-left corner of the keyboard. In the second row of numbers and symbols, press and hold your finger on the dollar-sign key. Above your finger, a box will pop up showing several currency symbols; these include the peso, the euro, the cent sign, the pound sterling and the yen.
The official ISO 4217 standard specifies three-letter ("Alpha-3") codes for currencies worldwide. The first two letters of these codes are usually identical with the two-letter ISO 3166-1 Alpha-2 country codes, which are well-known by internet users, as they are used for country domain suffixes.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With