【发布时间】:2010-10-26 17:15:49
【问题描述】:
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.01234];
//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.01234];
NSLog(@"%@",[doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]];
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;
【问题讨论】:
-
您要四舍五入吗?那应该是 1.4363 => "1.43" 还是 "1.44"?
-
我认为这是有道理的。
-
别忘了释放 doubleValueWithMaxTwoDecimalPlaces...
标签: iphone objective-c cocoa-touch decimal nsnumberformatter