Convert int to shortened, formatted string

前端 未结 2 1898
闹比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:27
    unsigned long long value = 1700llu;
    //value = 32600001llu;
    //value = UINT64_MAX;
    
    NSUInteger index = 0;
    double dvalue = (double)value;
    //Updated to use correct SI Symbol ( http://en.wikipedia.org/wiki/SI_prefix )
    NSArray *suffix = @[ @"", @"k", @"M", @"G", @"T", @"P", @"E" ];
    
    while ((value/=1000) && ++index) dvalue /= 1000;
    
    NSString *svalue = [NSString stringWithFormat:@"$%.*f%@",
                        //Use boolean as 0 or 1 for precision
                        (int)(dvalue < 100.0 && ((unsigned)((dvalue - (unsigned)dvalue) * 10) > 0)),
                        dvalue, [suffix objectAtIndex:index]];
    NSLog(@"Value: %@", svalue);
    

    ARC Localized Version

    unsigned long long value = 1700llu;
    //value = 32600001llu;
    //value = UINT64_MAX;
    
    NSUInteger index = 0;
    double dvalue = (double)value;
    //Updated to use correct SI Symbol ( http://en.wikipedia.org/wiki/SI_prefix )
    NSArray *suffix = @[ @"", @"k", @"M", @"G", @"T", @"P", @"E" ];
    
    while ((value/=1000) && ++index) dvalue /= 1000;
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    //Germany Example
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"de-de"]];
    //Set fractional digits to 0 or 1
    [formatter setMaximumFractionDigits:(int)(dvalue < 100.0 && ((unsigned)((dvalue - (unsigned)dvalue) * 10) > 0))];
    
    NSString *svalue = [[formatter stringFromNumber:[NSNumber numberWithFloat:dvalue]]
                        stringByAppendingString:[suffix objectAtIndex:index]];
    
    NSLog(@"Value: %@", svalue);
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题