38

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

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;
4

3 回答 3

45

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

    [doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
于 2010-10-26T17:51:55.360 回答
1
 NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
[numberFormatter setMinimumFractionDigits:2];
numberFormatter.positiveFormat = @"0.##";
NSNumber *num = @(total_Value);
于 2017-04-10T10:34:30.537 回答
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;
}
于 2010-10-26T18:05:54.640 回答