我读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