0

I am working on an app and I want to format a number such as 1,000,000 as a short string.

Some examples would be:

1000 => "1k"
50000 => "50k"
83952 => "84k"
1000000 => "1m"
1000000000 => "1b"

I was thinking the best way to do this would be using a NSNumberFormatter or just rounding it then counting the number of "0"'s. Anyone have an example of using a NSNumberFormatter in this manner or any resources to get started.

Sam Baumgarten
  • 2,231
  • 3
  • 21
  • 46

1 Answers1

0

You need to subclass the NSNumberFormatter:

Example:

@implementation LTNumberFormatter

@synthesize abbreviationForThousands;
@synthesize abbreviationForMillions;
@synthesize abbreviationForBillions;

-(NSString*)stringFromNumber:(NSNumber*)number
{
if ( ! ( abbreviationForThousands || abbreviationForMillions || abbreviationForBillions ) )
{
    return [super stringFromNumber:number];
}

double d = [number doubleValue];
if ( abbreviationForBillions && d > 1000000000 )
{
    return [NSString stringWithFormat:@"%@ %@", [super stringFromNumber:[NSNumber numberWithDouble:d / 1000000000]], abbreviationForBillions];
}
if ( abbreviationForMillions && d > 1000000 )
{
    return [NSString stringWithFormat:@"%@ %@", [super stringFromNumber:[NSNumber numberWithDouble:d / 1000000]], abbreviationForMillions];
}
if ( abbreviationForThousands && d > 1000 )
{
    return [NSString stringWithFormat:@"%@ %@", [super stringFromNumber:[NSNumber numberWithDouble:d / 1000]], abbreviationForThousands];
}
    return [super stringFromNumber:number];
}

@end
lakshmen
  • 28,346
  • 66
  • 178
  • 276