限制双精度到小数点后两位,不能有零

我读了这个和那个 。 我完全需要这个:

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; 

尝试添加以下行时,configuration您的格式化程序:

  [doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2]; 

如何修剪string末尾的不需要的字符?

 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; } 
  NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; [numberFormatter setRoundingMode:NSNumberFormatterRoundDown]; [numberFormatter setMinimumFractionDigits:2]; numberFormatter.positiveFormat = @"0.##"; NSNumber *num = @(total_Value);