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?
You can use the NSDecimalRound function
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)
value = (round(value*100)) / 100.0;
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]]);
In Swift 2.0 and Xcode 7.2:
let pi:Double = 3.14159265358979
String(format:"%.2f", pi)
Example:
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