NSNumberFormatter绝对是最好的选择!您可以在NSNumberFormatter上设置一个NSLocale,格式化程序将根据该语言环境自动运行。数字格式化程序的默认区域设置始终是用户所选区域格式的货币。
NSDecimalNumber *someAmount = [NSDecimalNumber decimalNumberWithString:@"5.00"];
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSLog(@"%@", [currencyFormatter stringFromNumber:someAmount]);
这将根据用户默认区域格式记录金额'5.00'。如果你想改变你可以设置的货币:
NSLocale *aLocale = [[NSLocale alloc] initWithLocaleIdentifier: "nl-NL"]
[currencyFormatter setLocale:aLocale];
这将选择该区域设置的默认货币。
虽然您不是以用户的本地货币收费,而是收费。要强制NSNumberFormatter
在货币格式,同时保持用户的偏好的数字格式,使用方法:
currencyFormatter.currencyCode = @"USD"
currencyFormatter.internationalCurrencySymbol = @"$"
currencyFormatter.currencySymbol = @"$"
在EN-US作为$5.00
在NL-NL这是$ 5,00
这将格式化。
这就是我的想法。我很好奇当用户在将someAmount归档到磁盘后更改其语言环境时会发生什么情况。 iPhone可以很容易地在另一个国家出差。如果用户对本地语言感到满意,他们可能会更改语言环境。当这个对象被解除存档时会发生什么?它会显示为创建和打算的“$ 5.00”,或者显示为“¥5”,显然,它具有明显不同的货币价值,但是当currencyFormatter的区域设置为日本时,格式正确的NSDecimalNumber为“5.00”。 – Meltemi 2009-05-13 16:32:54
您可以存储格式化或无格式的someAmount。如果将其格式化存储,金额将始终反映其制作币种。如果将其存储为未格式化,格式化程序将只将其格式化为当前的区域设置,但不会进行任何转换!因此:'$ 5.00'将变成'¥5'。我在我的应用程序中做的是存储未格式化的货币和它的区域设置。通过这种方式,我总是可以确定货币是在其生成的区域中进行格式化的,但我也可以稍后添加货币转换。 – klaaspieter 2009-05-14 08:40:31
只是通过c/p'ing此代码,我得到的警告:格式不是字符串文字和没有格式参数 我能不能得到这个? – oberbaum 2010-01-19 14:59:36