Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with NSNumberFormatter currencySymbol

I have a problem getting the currencySymbol of my NSNumberFormatter.
I use a NSNumberFormatter with a currency code "EUR".
When I format prices, the symbol is correct, I get the € symbol.
However, when I want to get just the currencySymbol with the method [formatter currencySymbol], the symbol $ is returned.
If I manually set the currencySymbol (with "A" for instance) everything will work fine and the method [formatter currencySymbol] will return the "A" symbol.


Here is my code

// Create formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setCurrencyCode:@"EUR"];
[formatter setLocale:[NSLocale currentLocale]];

// Log the currency symbol
NSLog(@"[formatter currencyCode] : %@", [formatter currencyCode]);
NSLog(@"[formatter currencySymbol] : %@", [formatter currencySymbol]);
NSLog(@"[formatter currencySymbol] : %@", [formatter stringFromNumber:[NSNumber numberWithInt:0]]);
[formatter setCurrencySymbol:@"A"];
NSLog(@"[formatter currencySymbol] : %@", [formatter currencySymbol]);
NSLog(@"[formatter currencySymbol] : %@", [formatter stringFromNumber:[NSNumber numberWithInt:0]]);

Here are the console results :

2012-01-17 12:29:11.108[4545:207] [formatter currencySymbol] : $
2012-01-17 12:29:11.109[4545:207] [formatter currencySymbol] : €0.00
2012-01-17 12:29:11.110[4545:207] [formatter currencySymbol] : A
2012-01-17 12:29:11.111[4545:207] [formatter currencySymbol] : A0.00

I cannot force the currencySymbol since it can change.
Is there a way to get the right currencySymbol corresponding to a given currencyCode ?

Thanks

like image 839
nicolas Avatar asked Jan 17 '12 11:01

nicolas


2 Answers

To get the currency symbol you can use NSLocaleCurrencySymbol with NSLocale:

   NSLocale* locale = [NSLocale currentLocale];
   NSString* cs = [locale displayNameForKey:NSLocaleCurrencySymbol
                                 value:currencyCode];

To get the localized name ('US Dollar', 'Japanese Yen', ..) you can use NSLocaleCurrencyCode:

   NSLocale* locale = [NSLocale currentLocale];
   NSString* cc = [locale displayNameForKey:NSLocaleCurrencyCode
                              value:currencyCode];

where currencyCode is the currency code (JPY, USD, EUR, ..) you're interested in.

like image 117
Jay Avatar answered Sep 28 '22 20:09

Jay


The issue might be that [formatter setLocale:[NSLocale currentLocale]]; overwrites some of the configuration you did prior to it. You may want to try movig that line to the top (just after the alloc/init line).

like image 43
Clafou Avatar answered Sep 28 '22 21:09

Clafou