iosobjective-cnsnumberformatternslocale

NSNumberFormatter - get currency symbol for currency code


This question is similar to, but there was no answer that worked on that question - NSNumberFormatter currency symbol


I am using an NSNumberFormatter to format currency values and this works fine as long as the currency is the currency of the user's locale. But I also need to show currency values that are possibly not the default currency for the user's locale (such as showing GBP when the current locale is en_US or showing JPY when the locale is fr_FR).

So I would like to display those currencies using the rules set by the current locale, but I do not know how to get the currency symbol after setting the currency code.

For example, here is how the NSNumberFormatter is configured:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.usesGroupingSeparator = YES;
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];

All those are correct. But then, if I set the currency code to GBP, like so:

currencyFormatter.currencyCode = @"GBP"

I get the following where the formatted string is correct and the currency code is correct, but the currency symbol and international currency symbol are incorrect.

But it is really weird to me that the stringFromNumber method would return the correctly formatted value, with the correct currency symbol but accessing the currencySymbol property directly returns the incorrect currency symbol.

I need to be able to access the currency symbol so I can make it smaller and shift its baseline so that the currency symbol is smaller and offset from the rest of the text.

Does anyone know if I am doing anything wrong or how to get the currency symbol after setting the currency code?


Solution

  • You're forcing currencyCode to 'GPD' but other properties of currency style as symbol, internationalCurrencySymbol, ... They depend on Locale. Check this:

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.usesGroupingSeparator = YES;
    formatter.numberStyle = NSNumberFormatterCurrencyStyle;
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_UK"];
    
    NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithDouble:123456]]);
    NSLog(@"%@", formatter.currencySymbol);
    NSLog(@"%@", formatter.currencyCode);
    NSLog(@"%@", formatter.internationalCurrencySymbol);
    

    It will print:

    £123,456.00
    £
    GBP
    GBP
    

    Then edit only the currency code to USD as the way you did:

    US$123,456.00
    £
    USD
    GBP