Round double value to 2 decimal places

前端 未结 12 1707
[愿得一人]
[愿得一人] 2020-11-29 18:15

I have a double value as 22.368511 I want to round it to 2 decimal places. i.e. it should return 22.37

How can I do that?

相关标签:
12条回答
  • 2020-11-29 19:11

    You can use the NSDecimalRound function

    0 讨论(0)
  • 2020-11-29 19:14

    You can use the below code to format it to two decimal places

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setMaximumFractionDigits:2];
    [formatter setRoundingMode: NSNumberFormatterRoundUp];
    
    NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:22.368511]];
    
    NSLog(@"Result...%@",numberString);//Result 22.37
    

    Swift 4:

    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.maximumFractionDigits = 2
    formatter.roundingMode = .up
    
    let str = String(describing: formatter.string(from: 12.2345)!)
    
    print(str)
    
    0 讨论(0)
  • 2020-11-29 19:15
     value = (round(value*100)) / 100.0;
    
    0 讨论(0)
  • 2020-11-29 19:15

    I was going to go with Jason's answer but I noticed that in My version of Xcode (4.3.3) I couldn't do that. so after a bit of research I found they had recently changed the class methods and removed all the old ones. so here's how I had to do it:

    NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
    
    [fmt setMaximumFractionDigits:2];
    NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);
    
    0 讨论(0)
  • 2020-11-29 19:17

    In Swift 2.0 and Xcode 7.2:

    let pi:Double = 3.14159265358979
    String(format:"%.2f", pi)
    

    Example:

    0 讨论(0)
  • 2020-11-29 19:19

    As in most languages the format is

    %.2f
    

    you can see more examples here


    Edit: I also got this if your concerned about the display of the point in cases of 25.00

    {
        NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
        [fmt setPositiveFormat:@"0.##"];
        NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);
        NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.3]]);
        NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.0]]);
    }
    
    2010-08-22 15:04:10.614 a.out[6954:903] 25.34
    2010-08-22 15:04:10.616 a.out[6954:903] 25.3
    2010-08-22 15:04:10.617 a.out[6954:903] 25
    
    0 讨论(0)
提交回复
热议问题