How can i get currency symbols from currency code in iphone?

前端 未结 9 846
庸人自扰
庸人自扰 2020-12-28 14:55

I have get currency code (Eg: USD, EUR, INR) from webservice response. I need to show the currency symbols for the corresponding currency code. If the currency code is USD,

相关标签:
9条回答
  • 2020-12-28 15:24

    NSLocale will happily tell you the currency symbol used by a particular locale:

    [locale objectForKey:NSLocaleCurrencySymbol];
    

    It'll also tell you the currency code:

    [locale objectForKey:NSLocaleCurrencyCode];
    

    So all you have to do now is look up the locale that corresponds to a given code. There's no built-in method (that I'm aware of) to do this directly, so loop through all the known locales and pick the one that matches. @Umka's answer has a good example of this in the -findLocaleByCurrencyCode: method.

    You could optimise the process by building your own lookup table, rather than iterating through all locales each time. You may need to handle the possibility of duplicate currency codes too, which would require some heuristic for deciding which is the most likely locale.

    0 讨论(0)
  • 2020-12-28 15:26
    NSNumberFormatter * formatter = [NSNumberFormatter new];
    formatter.numberStyle = NSNumberFormatterCurrencyStyle;
    
    NSString * localeIde = [NSLocale localeIdentifierFromComponents:@{NSLocaleCurrencyCode: currencyCode}];
    formatter.locale = [NSLocale localeWithLocaleIdentifier:localeIde];
    
    NSString * symbol = formatter.currencySymbol;
    
    0 讨论(0)
  • 2020-12-28 15:31

    Swift

    let locale = NSLocale(localeIdentifier: currencyCode)
    let currencySymbol = locale.displayName(forKey: .currencySymbol, value: currencyCode) ?? currencyCode
    print("Currency symbol: \(currencySymbol)")
    
    0 讨论(0)
提交回复
热议问题