Search code examples
iosobjective-cnsstringformatnsnumber

Reduce the number of digits in Number Formatter Objective-C


I have used a function to make numbers such as 123456 look like 123.456k. However I want the function to only have the first two decimals. So 123456 would like 123.46k. The function is shown here:

- (NSString*)numberWithShortcut:(NSNumber*)number
{
    unsigned long long value = [number longLongValue];

    NSUInteger index = 0;
    double dvalue = (double)value;

    NSArray *suffix = @[ @"", @"K", @"M", @"B", @"T", @"P", @"E" ];

    while ((value /= 1000) && ++index) dvalue /= 1000;

    NSString *svalue = [NSString stringWithFormat:@"%@%@",[NSNumber numberWithDouble:dvalue], [suffix objectAtIndex:index]];

    NSLog(svalue);

    return svalue;
}

Solution

  • Use number formatter

    NSNumberFormatter *formatter;
    [formatter setMaximumFractionDigits:2];
    

    The above is just one example of what you can do with it. Check Apple's documentation for more:

    https://developer.apple.com/LIBRARY/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/index.html