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 would say "$1.7k". If the user enters 32600000, the string would say "$32.6m".
Update
Here's the code I have so far. It seems to be working for numbers ~10k. I would just add more if statements for bigger numbers. But is there a more efficient way to do this?
NSNumberFormatter *nformat = [[NSNumberFormatter alloc] init];
[nformat setFormatterBehavior:NSNumberFormatterBehavior10_4];
[nformat setCurrencySymbol:@"$"];
[nformat setNumberStyle:NSNumberFormatterCurrencyStyle];
double doubleValue = 10200;
NSString *stringValue = nil;
NSArray *abbrevations = [NSArray arrayWithObjects:@"k", @"m", @"b", @"t", nil] ;
for (NSString *s in abbrevations)
{
doubleValue /= 1000.0 ;
if ( doubleValue < 1000.0 )
{
if ( (long long)doubleValue % (long long) 100 == 0 ) {
[nformat setMaximumFractionDigits:0];
} else {
[nformat setMaximumFractionDigits:2];
}
stringValue = [NSString stringWithFormat: @"%@", [nformat stringFromNumber: [NSNumber numberWithDouble: doubleValue]] ];
NSUInteger stringLen = [stringValue length];
if ( [stringValue hasSuffix:@".00"] )
{
// Remove suffix
stringValue = [stringValue substringWithRange: NSMakeRange(0, stringLen-3)];
} else if ( [stringValue hasSuffix:@".0"] ) {
// Remove suffix
stringValue = [stringValue substringWithRange: NSMakeRange(0, stringLen-2)];
} else if ( [stringValue hasSuffix:@"0"] ) {
// Remove suffix
stringValue = [stringValue substringWithRange: NSMakeRange(0, stringLen-1)];
}
// Add the letter suffix at the end of it
stringValue = [stringValue stringByAppendingString: s];
//stringValue = [NSString stringWithFormat: @"%@%@", [nformat stringFromNumber: [NSNumber numberWithDouble: doubleValue]] , s] ;
break ;
}
}
NSLog(@"Cash = %@", stringValue);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…