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
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);
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;
}