I have a problem with reading and writing NSDecimalNumbers. Say I have this decimal number:
NSDecimalNumber *myNumber; // this is 123,23
Then I read its value like this and show it in a textField
self.textField.text = [NSString stringWithFormat:@"%@", myNumber];
It'll look like this in a textField: "123.23", notice the dot instead of a comma. If I try to read it into the property again like so, the decimals are excluded. 123 is the only thing that gets read:
myNumber = [NSDecimalNumber decimalNumberWithString:self.textField.text];
But if I write 123,23 with the keyboard using UIKeyboardTypeDecimalPad and a comma, it works just fine. Why is this?
Thanks!
Formatting decimal numbers is a problem. Usually, instead of just using
%@
withmyNumber
, which uses[NSDecimalNumber description]
, you have to use[NSDecimalNumber descriptionWithLocale:]
. That will localize the decimal separator.If you need other formatting, for example limiting the number of decimal digits or adding grouping separators, you can use
NSNumberFormatter
, howeverNSNumberFormatter
converts all numbers todouble
first, so you will always lose precision.The more robust solution when formatting
NSDecimalNumber
is rolling your own formatter.