iOS Dev
iOS Dev

Reputation: 4248

Loosing fractional zeros when formatting a NSDecimalNumber with NSNumberFormatter

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?

Upvotes: 3

Views: 800

Answers (3)

iOS Dev
iOS Dev

Reputation: 4248

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"]];

Upvotes: 2

Fran Martin
Fran Martin

Reputation: 2369

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

Upvotes: 1

Caleb
Caleb

Reputation: 124997

Add this:

[numberFormatter setMinimumFractionDigits:3];

Upvotes: 4

Related Questions