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

では、最大小数点以下 2 桁で double 値をフォーマットするにはどうすればよいでしょうか? 最後の位置にゼロが含まれている場合は、ゼロを除外する必要があります。

解決:

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 に答える
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 に答える