用户将输入美元值作为int
,我想将结果转换为缩短的格式化字符串。所以如果用户输入1700,字符串会说“$ 1.7k”。如果用户输入32600000,字符串将会说“$ 32.6m”。将int转换为缩短的格式化字符串
更新
这里是我到目前为止的代码。它似乎正在为数字〜10K工作。我只是添加更多的if语句为更大的数字。但是,有没有更有效的方法来做到这一点?
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);
你可以做到这一点一个简单的if ... else if ... – Selkie 2012-08-16 19:09:16
我相信你在问你的问题之前已经尝试了一些东西,但是你的代码没有工作。你可以请你尽最大努力吗? – dasblinkenlight 2012-08-16 19:09:53
虽然你会如何得到小数点?即,将1700转换为1.7。我认为这就是我正在努力的。在将其转换为字符串之前将其分开? – bmueller 2012-08-16 19:12:53