Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

cocoa touch - Localize Currency for iPhone

I would like my iPhone app to allow the input, display and storage of currency amounts using the appropriate symbol ($, €, ?, ¥, etc) for the user.

Would NSNumberFormatter do everything I need? What happens when a user switches their locale and these amounts (dollars, yen, etc.) are stored as NSDecimalNumbers. I assume, to be safe, it's necessary to somehow capture the locale at the time of entry and then the currency symbol and store them in my instance along with the NSDecimalNumber ivar so they can be unwrapped and displayed appropriately down the road should the user changed their locale since the time when the item was created?

Sorry, I have little localization experience so hoping for a couple quick pointers before diving in. Lastly, any insight on how to you handle this kind of input given the limitations of the iPhone's keyboards?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

NSNumberFormatter is definitely the way to go! You can set a NSLocale on the NSNumberFormatter, the formatter will automatically behave according to that locale. The default locale for a number formatter is always the currency for the users selected region format.

NSDecimalNumber *someAmount = [NSDecimalNumber decimalNumberWithString:@"5.00"];

NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

NSLog(@"%@", [currencyFormatter stringFromNumber:someAmount]);

This will log the amount '5.00' according to the users default region format. If you want to alter the currency you can set:

NSLocale *aLocale = [[NSLocale alloc] initWithLocaleIdentifier: "nl-NL"]
[currencyFormatter setLocale:aLocale];

Which will choose the default currency for that locale.

Often though you're not charging in your user's local currency, but in your own. To force NSNumberFormatter to format in your currency, while keeping the number formatting in the user's preference, use:

currencyFormatter.currencyCode = @"USD"
currencyFormatter.internationalCurrencySymbol = @"$"
currencyFormatter.currencySymbol = @"$"

In en-US this will format as $5.00 in nl-NL it's $ 5,00.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...