Read and write an NSDecimalNumber

181 views Asked by At

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!

4

There are 4 answers

0
Sulthan On BEST ANSWER

Formatting decimal numbers is a problem. Usually, instead of just using %@ with myNumber, which uses [NSDecimalNumber description], you have to use [NSDecimalNumber descriptionWithLocale:]. That will localize the decimal separator.

self.textField.text = [NSString stringWithFormat:@"%@", [myNumber descriptionWithLocale:[NSLocale currentLocale]];

If you need other formatting, for example limiting the number of decimal digits or adding grouping separators, you can use NSNumberFormatter, however NSNumberFormatter converts all numbers to double first, so you will always lose precision.

The more robust solution when formatting NSDecimalNumber is rolling your own formatter.

1
Vikash Rajput On
self.textField.text = [NSString stringWithFormat:@"%@,", myNumber];
0
Santu C On

Please check with below code -

self.textField.text = [NSString stringWithFormat:@"%@",[NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterDecimalStyle]];
0
Bhadresh Mulsaniya On
NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithString:@"120000"];
NSLocale *priceLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-in"]; 

NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setLocale:priceLocale];
NSString *format = [currencyFormatter positiveFormat];
[currencyFormatter setPositiveFormat:format];

NSString *currencyString1 = [currencyFormatter stringFromNumber:price];
DLog(@"%@",currencyString1);