Search code examples
iosobjective-ccocoa-touchnsnumberformatter

NSNumberFormatter does not format correctly


I am working on a simple app that requires NSNumberFormatter. I am trying to get a number rounded off to 2 decimal places with the following code:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.locale = [NSLocale currentLocale];
formatter.formatterBehavior = NSNumberFormatterBehaviorDefault;
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.usesSignificantDigits = NO;

formatter.maximumFractionDigits = 2;
NSLog(@"%@",[formatter numberFromString:@"123.12345"]);

However, the log output comes out as:

123.12345

I am totally stumped as to why this is happening.


Solution

  • NSNumber *num = [formatter numberFromString:@"123.12345"];
    NSLog(@"num: %@", num);
    

    That created an NSNumber from the string value. NSNumber does not have any formatting, just the value. The NSNumber could have been created in any number of different ways such as @123.12345.

    Now create an NSString with the desired formatting from the NSNumber:

    NSString *strNum = [formatter stringFromNumber:@123.12345];
    NSLog(@"strNum: %@", strNum);
    

    NSLog output:

    num: 123.12345
    strNum: 123.12