我讀this和that。我想這恰好:限制一個雙精度到小數點後兩位的小數位
1.4324 => 「1.43」
9.4000 => 「9.4」
43.000 => 「43」9.4 => 「9.40」(錯誤)
43.000 = >「43.00」(錯誤)
在兩個問題中,答案均指向NSNumberFormatter
。所以它應該很容易實現,但不適合我。
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 20)];
NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setPaddingPosition:NSNumberFormatterPadAfterSuffix];
[doubleValueWithMaxTwoDecimalPlaces setFormatWidth:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.];
//NSNumber *myValue = [NSNumber numberWithDouble:0.1];
myLabel.text = [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue];
[self.view addSubview:myLabel];
[myLabel release];
myLabel = nil;
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;
}
我也
NSString *resultString = [NSString stringWithFormat: @"%.2lf", [myValue doubleValue]];
NSLog(@"%@", resultString);
所以試了一下我怎麼能以最大的兩位小數格式化雙重價值?如果最後一個位置包含一個零,則應該省略零。
解決方案:
NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.];
NSLog(@"%@",[doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]];
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;
你想四捨五入嗎?那應該是1.4363 =>「1.43」或「1.44」? – 2010-10-26 17:48:50
我認爲這是有道理的。 – testing 2010-10-26 17:50:44
畢竟不要忘了發佈doubleValueWithMaxTwoDecimalPlaces ... – Lukasz 2010-12-15 22:23:35