[iphone] Round double value to 2 decimal places

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?

This question is related to iphone objective-c cocoa-touch

The answer is


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

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)

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

[label setText:@"Value: %.2f", myNumber];

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

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

 value = (round(value*100)) / 100.0;

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


You can use the NSDecimalRound function


In Swift 2.0 and Xcode 7.2:

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

Example:

enter image description here


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

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?