With my language and region being set to 'en_US', I can save a decimal number ex: 0.55 in core data and upon loading the correct value is retrieved.
If I change my region to 'en_PT' i.e. to test out the formatting of currency amounts, saving the same number 0,55 gets rounded up to '0'
I have tested this on the simulator and device and I see the same behavior. The 'amount' field in coreData model is 'Decimal'. Is there anything specific I need to do in CoreData to support this ?
Here's different parts of my code ... saving to 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];
}
Retrieving from 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];
}
Converting the user entering amount from a textfield to an NSDecimal number
+(NSDecimalNumber*) decimalNumberFromUserEnteredString:(NSString*)string
{
NSNumber *number = [[NSNumberFormatter cachedAmountFormatter] numberFromString:string];
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithDecimal:[number decimalValue]];;
return decimalNumber;
}
Here is the formatter ...
+(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;
}