限制一个双精度到两位小数,不带尾随零

tes*_*ing 37 iphone cocoa-touch decimal objective-c nsnumberformatter

我读了这个那个.我想要这个:

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;
}
Run Code Online (Sandbox Code Playgroud)

我也试过了

NSString *resultString = [NSString stringWithFormat: @"%.2lf", [myValue doubleValue]];
NSLog(@"%@", resultString);
Run Code Online (Sandbox Code Playgroud)

那么如何格式化最多两位小数的双值?如果最后一个位置包含零,则应省略零.

解:

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;
Run Code Online (Sandbox Code Playgroud)

小智 44

配置格式化程序时,请尝试添加以下行:

    [doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
Run Code Online (Sandbox Code Playgroud)