Search code examples
objective-cnsnumberformatternsformatter

NSNumberFormatter: Displaying zero as last digit starting from a string like 25.0


I have a string that represents a float, for example 2400.0. I want to format it as digit (2,400.0) and I need to keep the zero after the digit symbol.

NSString* theString = @"2400.0"; 

// I convert the string to a float 
float f = [theString floatValue]; 
// here I lose the digit information :( and it ends up with 2400 instead of 2400.0

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesSignificantDigits:YES];
[formatter setMinimumFractionDigits:1];
[formatter setMaximumFractionDigits:2];
[formatter setLocale:[NSLocale currentLocale]];

NSString *result = [formatter stringFromNumber:@(f)];

The NSLog of result is 2,400 while I need 2,400.0

How can I obtain the right string?


Solution

  • You probably want to set the minimumFractionDigits to 1 (and your maximumFractionDigits as well in this case).

    You also probably don't want to use significant digits. The following code yields the desired output:

    NSString *theString = @"2400.0";
    
    float f = [theString floatValue];
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setMinimumFractionDigits:1];
    [formatter setMaximumFractionDigits:1];
    [formatter setLocale:[NSLocale currentLocale]];
    
    NSLog(@"%@", [formatter stringFromNumber:@(f)]);