我正在开发一个应用程序,我希望将一个数字(例如1,000,000)格式化为短字符串。
一些例子是:
1000 => "1k"
50000 => "50k"
83952 => "84k"
1000000 => "1m"
1000000000 => "1b"
我认为最好的方法是使用NSNumberFormatter或者只是将其四舍五入然后计算" 0"的数量。任何人都有以这种方式使用NSNumberFormatter的示例或任何资源来开始。
答案 0 :(得分:0)
您需要子类化NSNumberFormatter:
示例:
@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