本地化iPhone的货币

Mel*_*emi 16 iphone cocoa-touch localization currency

我希望我的iPhone应用程序允许使用适当的符号($,€,₤,¥等)为用户输入,显示和存储货币金额.

NSNumberFormatter会做我需要的一切吗?用户切换其区域设置时会发生什么,这些金额(美元,日元等)存储为NSDecimalNumbers.我假设,为了安全起见,有必要以某种方式捕获输入时的区域设置,然后是货币符号并将它们与NSDecimalNumber ivar一起存储在我的实例中,以便在用户更改时可以将它们展开并在路上正确显示自项目创建以来他们的语言环境?

对不起,我没有很少的本地化经验,所以希望在潜入之前提供一些快速指示.最后,考虑到iPhone键盘的限制,有关如何处理这种输入的任何见解?

kla*_*ter 32

NSNumberFormatter绝对是您要走的路!您可以在NSNumberFormatter上设置NSLocale,格式化程序将根据该语言环境自动运行.数字格式化程序的默认语言环境始终是用户所选区域格式的货币.

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

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

NSLog(@"%@", [currencyFormatter stringFromNumber:someAmount]);
Run Code Online (Sandbox Code Playgroud)

这将根据用户默认区域格式记录金额"5.00".如果您想更改您可以设置的货币:

NSLocale *aLocale = [[NSLocale alloc] initWithLocaleIdentifier: "nl-NL"]
[currencyFormatter setLocale:aLocale];
Run Code Online (Sandbox Code Playgroud)

这将选择该区域设置的默认货币.

通常情况下,您不是按照用户的本地货币收费,而是自己收费.要强制NSNumberFormatter使用您的货币格式化,同时在用户首选项中保留数字格式,请使用:

currencyFormatter.currencyCode = @"USD"
currencyFormatter.internationalCurrencySymbol = @"$"
currencyFormatter.currencySymbol = @"$"
Run Code Online (Sandbox Code Playgroud)

在en-US中,这将格式化为$5.00nl-NL $ 5,00.