I have currency code (for example: "UAH"). In my code I get currency symbol equal currency code ("UAH"), but for "USD" and "EUR" - "$" and "€". Why?
let currencyCode = "UAH"
let localeComponents = [NSLocaleCurrencyCode: currencyCode]
let localeIdentifier = NSLocale.localeIdentifierFromComponents(localeComponents)
let locale = NSLocale(localeIdentifier: localeIdentifier)
let currencySymbol = locale.objectForKey(NSLocaleCurrencySymbol)
I found solution:
let locales: NSArray = NSLocale.availableLocaleIdentifiers()
for localeID in locales as! [NSString] {
let locale = NSLocale(localeIdentifier: localeID as String)
let code = locale.objectForKey(NSLocaleCurrencyCode) as? String
if code == "UAH" {
let symbol = locale.objectForKey(NSLocaleCurrencySymbol) as? String
print(symbol!)
break
}
}
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.
Etymologically, the word 'cent' derives from the Latin word centum meaning hundred. The cent sign is commonly a simple minuscule (lower case) letter c. In North America, the c is crossed by a diagonal stroke or a vertical line (depending on typeface), yielding the character ¢.
Because your locale
wasn't set up correctly. The system knows nothing about your locale other than its currency code. There are two dozens or so locales with USD
as the currency code; their currency symbols vary between US$
and $
. UAH
has 2 available locales: ru_UA
and uk_UA
.
A safer way is to iterate over all locales that have the same currency code as you have specified, then use a rule to pick from the resulting list:
let currencyCode = "UAH"
let currencySymbols = NSLocale
.availableLocaleIdentifiers()
.map { NSLocale(localeIdentifier: $0) }
.filter {
if let localeCurrencyCode = $0.objectForKey(NSLocaleCurrencyCode) as? String {
return localeCurrencyCode == currencyCode
} else {
return false
}
}
.map {
($0.localeIdentifier, $0.objectForKey(NSLocaleCurrencySymbol)!)
}
print(currencySymbols) // Now you can choose from the list
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