Convert int to shortened, formatted string

前端 未结 2 1914
闹比i
闹比i 2020-12-06 08:22

The user will enter a dollar value as an int, and I\'d like to convert the result into a shortened, formatted string. So if the user enters 1700, the string wou

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 08:44

    If you want a string with auto-adjustable width you can use:

    +(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]];
    
        return svalue;
    }
    

提交回复
热议问题