1.4324 => "1.43"
9.4000 => "9.4"
43.000 => "43"9.4 => "9.40" (wrong)
43.000 => "43.00" (wrong)
这两个问题的答案都指向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);
那么如何格式化最多两位小数的 double 值?如果最后一个位置包含零,则应省略零。
解决方案:
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;
最佳答案
在配置格式化程序时尝试添加以下行:
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
关于iphone - 将 double 限制为两位小数,不带尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4026135/