开发者

Limit a double to two decimal places without trailing zeros

I read this and that. I want this exactly:

1.4324 => "1.43"

9.4000 => "9.4"

43.000 => "43"

9.4 => "9.40" (wrong)

43.000 => "43.00" (wrong)

In both questions the answers points to NSNumberFormatter. So it should be easy to achieve, but not for me.

- (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;
}

I also tried it with

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

So how can I format double values with maximum two decimal places? If the last position contains a zero the zero should be left out.

Solution:

NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[double开发者_开发问答ValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.01234];
NSLog(@"%@",[doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]];
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;


Try adding the following line, when configuring your formatter:

    [doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];


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


How about trimming the unwanted characters from the end of the string?:

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜