3

I use the following code to format string numbers by adding thousand separation points:

NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:@"0.000"];
NSLog(@"decimalNumber = %@",decimalNumber);

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setGroupingSeparator:@"."];
[numberFormatter setGroupingSize:3];
[numberFormatter setUsesGroupingSeparator:YES];
[numberFormatter setDecimalSeparator:@","];
[numberFormatter setMaximumFractionDigits:9];

NSString *finalString = [numberFormatter stringFromNumber:decimalNumber];
NSLog(@"finalString = %@",finalString);

And if I want to format @"0.000" string (it's not necessary to be 3 zeros, there can be less or much more) I have the following log output:

decimalNumber = 0
finalString = 0

but what I want is to keep fraction zeros, i.e in this case my string must remain unchanged. I see that these zeros are lost when I create the NSDecimalNumber, and I need another approach. What can be it?

iOS Dev
  • 4,143
  • 5
  • 30
  • 58

3 Answers3

4

Add this:

[numberFormatter setMinimumFractionDigits:3];
Caleb
  • 124,013
  • 19
  • 183
  • 272
  • And `[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];` – Desdenova Feb 25 '14 at 13:13
  • It's useful only in case when there are exactly three zeros after point, but it was just an example. It doesn't work when I have for example: @"0.0000" – iOS Dev Feb 25 '14 at 13:16
  • Yes, the `3` was just an example. You can replace it with a different number, or even with a variable as in: `[numberFormatter setMinimumFractionDigits:significantDigitsAfterDecimalPoint];` But the formatter can't tell how many zeros you might want, so you need to keep track and tell it. – Caleb Feb 25 '14 at 13:20
2

Caleb's answer helped me to solve the issue, and I would like to share how I completely fixed it:

1.First I added this method:

- (uint) fractionalNumberCountFromString:(NSString*) numberString
{
    NSRange fractionalPointRange = [numberString rangeOfString:@"."];
    if (fractionalPointRange.location == NSNotFound)
    {
        return 0;
    }
    return numberString.length-fractionalPointRange.location-1;
}

2.Second I added this line where I'm setting the NSNumberFormatter:

[numberFormatter setMinimumFractionDigits:[self fractionalNumberCountFromString:@"0.000"]];
iOS Dev
  • 4,143
  • 5
  • 30
  • 58
1

Try this way

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"US"];

NSNumberFormatter *formatterN = [[NSNumberFormatter alloc] init];
[formatterN setMaximumFractionDigits:3];
[formatterN setMinimumFractionDigits:3];
[formatterN setLocale:usLocale];

[formatterN stringFromNumber:decimalNumber];
Fran Martin
  • 2,369
  • 22
  • 19