我的应用程序使用货币值,我想以用户在 iPhone 上设置的货币和格式表示这些值,但是,在测试时,我似乎遇到了德国 EURO 格式的问题。
我有一个从货币格式化字符串返回十进制数(用于存储在核心数据中)的方法。该字符串实际上是由另一个(类似的)方法使用 NSlocale 格式化的。
我已经在英国、美国、日本和德国地区进行了测试,到目前为止只有德国造成了任何问题。
这是代码,传递的字符串例如:2,56 €</p>
+ (NSDecimalNumber*)TLCurrencyFormatFromString:(NSString*)strNumber {
NSNumberFormatter *fmtrCurrencyFromStr = nil;
fmtrCurrencyFromStr = [[NSNumberFormatter alloc] init];
[fmtrCurrencyFromStr setFormatterBehavior:NSNumberFormatterBehavior10_4];
[fmtrCurrencyFromStr setLocale:[NSLocale currentLocale]];
[fmtrCurrencyFromStr setNumberStyle:NSNumberFormatterCurrencyStyle];
[fmtrCurrencyFromStr setGeneratesDecimalNumbers:YES];
NSLog(@"Currency Separator: %@", [fmtrCurrencyFromStr decimalSeparator]); //prints a comma
NSLog(@"Currency Code: %@", [fmtrCurrencyFromStr currencyCode]); //prints EUR
int currencyScale = [fmtrCurrencyFromStr maximumFractionDigits];
NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:currencyScale raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE];
NSDecimalNumber* currencyNumber = [[NSDecimalNumber alloc] initWithDecimal:[[fmtrCurrencyFromStr numberFromString:strNumber] decimalValue]];
NSLog(@"Currency Number = %@", [currencyNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior]);
return [currencyNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
}
“currencyNumber”变量打印为:-1844691245360747053200000000000000000000000000000000000000000000000000000000000000000000000000000
而在所有其他语言环境中,它将打印 2.56 以作为 NSDecimalNumber 存储到 Core Data 中。