Round double value to 2 decimal places

前端 未结 12 1706
[愿得一人]
[愿得一人] 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 18:55

    I use the solution posted by Umberto Raimondi extending type Double:

    extension Double {
        func roundTo(places:Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return (self * divisor).rounded() / divisor
        }
    }
    
    0 讨论(0)
  • 2020-11-29 18:57

    For Swift there is a simple solution if you can't either import Foundation, use round() and/or does not want a String (usually the case when you're in Playground):

    var number = 31.726354765
    var intNumber = Int(number * 1000.0)
    var roundedNumber = Double(intNumber) / 1000.0
    

    result: 31.726

    0 讨论(0)
  • 2020-11-29 18:59

    You could do this:

    NSNumberFormatter* f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    [f setFormat:@0.00"];
    
    // test
    NSNumber* a = @12;
    NSString* s = [f stringFromNumber:a];
    NSLog(@"%@", s);
    
    0 讨论(0)
  • 2020-11-29 19:05

    Use NSNumber *aNumber = [NSNumber numberWithDouble:number]; instead of NSNumber *aNumber = [NSNumber numberWithFloat:number];

    +(NSString *)roundToNearestValue:(double)number
    {
        NSNumber *aNumber = [NSNumber numberWithDouble:number];
    
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [numberFormatter setUsesGroupingSeparator:NO];
        [numberFormatter setMaximumFractionDigits:2];
        [numberFormatter setMinimumFractionDigits:0];
        NSString *string = [numberFormatter stringFromNumber:aNumber];        
        return string;
    }
    
    0 讨论(0)
  • 2020-11-29 19:08
    [label setText:@"Value: %.2f", myNumber];
    
    0 讨论(0)
  • 2020-11-29 19:09

    To remove the decimals from your double, take a look at this output

    Obj C

    double hellodouble = 10.025;
    NSLog(@"Your value with 2 decimals: %.2f", hellodouble);
    NSLog(@"Your value with no decimals: %.0f", hellodouble);
    

    The output will be:

    10.02 
    10
    

    Swift 2.1 and Xcode 7.2.1

    let hellodouble:Double = 3.14159265358979
    print(String(format:"Your value with 2 decimals: %.2f", hellodouble))
    print(String(format:"Your value with no decimals: %.0f", hellodouble))
    

    The output will be:

    3.14 
    3
    
    0 讨论(0)
提交回复
热议问题