Подтвердить что ты не робот

Ограничьте два-два десятичных знака без конечных нулей

Я прочитал этот и который. Я хочу это точно:

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

Ответ 1

Попробуйте добавить следующую строку при настройке форматирования:

    [doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];

Ответ 2

Как обрезать нежелательные символы из конца строки?:

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

 NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
[numberFormatter setMinimumFractionDigits:2];
numberFormatter.positiveFormat = @"0.##";
NSNumber *num = @(total_Value);