1

When I try to convert number 999999999 to string using NSNumberFormatter, I am getting wrong value. It returns 1,000,000,000 instead of 999,999,999.

Here is the code that I use.

 NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setUsesSignificantDigits:YES];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:[NSLocale systemLocale]];
[numberFormatter setCurrencySymbol:@""];

numberAsString = [numberFormatter stringFromNumber:[NSDecimalNumber decimalNumberWithString:@"999999999" ]];
NSLog(@"Currency String %@",numberAsString);
arundevma
  • 933
  • 7
  • 24
  • Why do you need to convert it to a decimal number, pass it through a formatter (that's configured as a currency formatter??), and pass it back into a string? – Schemetrical Apr 09 '15 at 12:34
  • 1
    offtopic: use dot notation for properties as suggested in many objc styleguide's – CarlJ Apr 09 '15 at 12:47

2 Answers2

2

You specified to use significant digits, but didn't say how many to use. For example, if you add the following, you get the result you were expecting:

[numberFormatter setMaximumSignificantDigits:9];

So, if you're going to use significant digits, specify how many you want to use. Or don't use significant digits at all.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
2

You enabled usesSignificantDigits. Default value for maximumSignificantDigits is 6. Which means every number with more than 6 significant digits will be rounded to have less than 6 significant digits.

999 999 999 has 9 significant digits. So it will be rounded to 1 000 000 000

You probably don't want to set usesSignificantDigits at all.

Here is a good explanation what significant digits do with NSNumberFormatter.

Community
  • 1
  • 1
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247