Home > Software design >  Objective-C: how to convert from currency symbol € to currency code EUR and show it on a label?
Objective-C: how to convert from currency symbol € to currency code EUR and show it on a label?

Time:09-16

Is there a way to convert a currency symbol in the currency code?

In my case I want to convert the symbol € to currency code EUR and show it in a UILabel. It must work even if the device settings are set to another Region (USA for example, and it has to show USD of course).

I've seen different examples on Stackoverflow but they show the opposite. Any suggestions?

CodePudding user response:

Get code for specified locale, locale matters because the same symbol like $ can give different codes, for instance en-US gives USD and en-ca gives CAD

- (NSString *)currencyCodeWithCurrencySymbol:(NSString *)currencySymbol
                                      locale:(NSLocale *)locale
{
    for (NSString *code in [NSLocale ISOCurrencyCodes]) {
        NSString *symbol = [locale displayNameForKey:NSLocaleCurrencySymbol value:code];

        if ([symbol isEqualToString:currencySymbol]) {
            return code;
        }
    }

    return nil;
}

CodePudding user response:

You can enumerate the available locales and find the one with your currency symbol:

- (nullable NSString *)currencyCodeForCurrencySymbol:(NSString *)currencySymbol {
    for (NSString *localeId in [NSLocale availableLocaleIdentifiers]) {
        NSLocale *locale = [NSLocale localeWithLocaleIdentifier:localeId];
        if ([currencySymbol isEqual:[locale objectForKey: NSLocaleCurrencySymbol]]) {
            return [locale objectForKey: NSLocaleCurrencyCode];
        }
    }
    return NULL;
}
  • Related