我的语言和区域设置为'en_US',我可以在核心数据中保存十进制数:0.55,并在加载时检索正确的值。
如果我将我的区域更改为'en_PT',即测试货币金额的格式,则保存相同的数字0,55将向上舍入为'0'
我在模拟器和设备上测试了这个,我看到了相同的行为。 coreData模型中的'amount'字段是'Decimal'。我在CoreData中需要做些什么来支持这个吗?
以下是我的代码的不同部分...保存到coreData
-(void)addPayment:(Payment*)payment withContext:(NSManagedObjectContext *)context onSuccess:(SuccessBlock)successBlock onFailed:(FailedBlock)failedBlock
{
CDPayments* cdPayment = [NSEntityDescription insertNewObjectForEntityForName:PAYMENTS_TABLE
inManagedObjectContext:context];
[self copyPayment:payment intoCDPayment:cdPayment];
[self saveDataInContext:context onSuccess:successBlock onError:failedBlock];
}
从coreData中检索
-(void) listOfPaymentsWithFilter:(NSPredicate*)predicate onSuccess:(SuccessNSArrayBlock)successBlock onFailed:(FailedBlock)failedBlock
{
[self listOfAllObjectsForEntity:EntityTypePayments filterWith:predicate sortBy:nil
onSuccess:^(NSArray *array)
{
NSMutableArray *paymentsList = [[NSMutableArray alloc] init];
for (CDPayments* cdPayment in array)
{
Payment* tmpPayment = [[Payment alloc] init];
[self copyPayment:tmpPayment fromCDPayment:cdPayment];
[paymentsList addObject:tmpPayment];
}
successBlock(paymentsList);
}
onError:failedBlock];
}
将用户输入金额从文本字段转换为NSDecimal数字
+(NSDecimalNumber*) decimalNumberFromUserEnteredString:(NSString*)string
{
NSNumber *number = [[NSNumberFormatter cachedAmountFormatter] numberFromString:string];
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithDecimal:[number decimalValue]];;
return decimalNumber;
}
这是格式化程序......
+(NSNumberFormatter*) cachedAmountFormatter
{
if (cachedNumberFormatter == nil)
{
cachedNumberFormatter = [[NSNumberFormatter alloc] init];
cachedNumberFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
cachedNumberFormatter.lenient = YES;
cachedNumberFormatter.minimumFractionDigits = 2;
cachedNumberFormatter.maximumFractionDigits = 2;
cachedNumberFormatter.locale = [NSLocale currentLocale];
}
return cachedNumberFormatter;
}