Erik
Erik

Reputation: 2530

Read and write an NSDecimalNumber

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!

Upvotes: 0

Views: 190

Answers (4)

Sulthan
Sulthan

Reputation: 130102

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.

Upvotes: 1

Bhadresh Mulsaniya
Bhadresh Mulsaniya

Reputation: 2640

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);

Upvotes: 0

Vikash Rajput
Vikash Rajput

Reputation: 455

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

Upvotes: 0

Santu C
Santu C

Reputation: 2654

Please check with below code -

self.textField.text = [NSString stringWithFormat:@"%@",[NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterDecimalStyle]];

Upvotes: 0

Related Questions