代码之家  ›  专栏  ›  技术社区  ›  testing

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

  •  36
  • testing  · 技术社区  · 13 年前

    我读过 this that . 我想要这个:

    1.4324=>“1.43”
    9.4000=>“9.4”
    43.000=>“43”

    9.4=>“9.40”(错误)

    两个问题的答案都指向 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;
    
    3 回复  |  直到 7 年前
        1
  •  44
  •   Chris Gummer    13 年前

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

        [doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
    
        2
  •  0
  •   PeyloW    13 年前

    把字符串末尾不需要的字符剪下来怎么样?:

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