0

我正在开发一个应用程序,我想将一个数字(例如 1,000,000)格式化为一个短字符串。

一些例子是:

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

我在想最好的方法是使用NSNumberFormatter或者只是四舍五入然后计算“0”的数量。任何人都有以这种方式使用 NSNumberFormatter 的示例或任何开始使用的资源。

4

1 回答 1

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
于 2013-07-29T00:07:14.980 回答