I am trying to create a NSDecimalNumber to store a currency value in Core Data based in a string that contains the value 11.90. I want to keep the 2 decimals but the 0 is being ignored and it always turns 11.9 as NSDecimalNumber. I tried to use the Behavior protocol rounding and add the scale but it didn't work for me.
Is it working as designed and should I just use a formatter to add the 0 when retrieving the 11.9 from Core Data or is there any step I'm missing ?
Thanks.
NSDecimalNumberHandler *behavior = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundPlain
scale:2
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:NO];
[NSDecimalNumber setDefaultBehavior:behavior];
NSDecimalNumber *priceDecimal;
NSDictionary *locale = [NSDictionary dictionaryWithObject:currentLocaleSeparator forKey:NSLocaleDecimalSeparator];
priceDecimal = [NSDecimalNumber decimalNumberWithString:price locale:locale];
priceDecimal = [priceDecimal decimalNumberByRoundingAccordingToBehavior:behavior];
Right, the formatter is the right approach. You have to distinguish between the precision of the decimal number being stored, which seems to be working fine, and its representation or formatting.
I have made lots of apps with currencies - I have always found that it is easier and more convenient to simply count the cents (or hundreds unit) using 64 bit Integers.
Check out NSNumberFormatter
's minimumFractionDigits
.