用戶將輸入美元值作爲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