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;
答案 0 :(得分:42)
在配置格式化程序时尝试添加以下行:
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
答案 1 :(得分:0)
如何从字符串末尾修剪不需要的字符?:
NSString* CWDoubleToStringWithMax2Decimals(double d) {
NSString* s = [NSString stringWithFormat:@"%.2f", d];
NSCharacterSet* cs = [NSCharacterSet characterSetWithCharacterInString:@"0."];
NSRange r = [s rangeOfCharacterInSet:cs
options:NSBackwardsSearch | NSAnchoredSearch];
if (r.location != NSNotFound) {
s = [s substringToIndex:r.location];
}
return s;
}
答案 2 :(得分:0)
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
[numberFormatter setMinimumFractionDigits:2];
numberFormatter.positiveFormat = @"0.##";
NSNumber *num = @(total_Value);