Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round doubles in Objective-C

I have double number in a format like 34.123456789. How can I change it to 34.123?

I just want 3 digits after the decimal point.

like image 450
Amir Avatar asked Aug 13 '10 11:08

Amir


4 Answers

If you want to make

34.123456789 -> 34.123
34.000000000 -> 34 not 34.000

You can use NSNumberFormatter

NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setMaximumFractionDigits:3]; // 3 is the number of digits

NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:34.123456789]]);  // print 34.123
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:34.000000000]]);  // print 34
like image 154
Linh Avatar answered Nov 11 '22 06:11

Linh


The approved solution has a small typo. It's missing the "%".

Here is the solution without the typo and with a little extra code.

double d = 1.23456;
NSString* myString = [NSString stringWithFormat:@"%.3f",d];

myString will be "1.234".

like image 37
Blamdarot Avatar answered Nov 11 '22 05:11

Blamdarot


You can print it to 3 decimal places with [NSString stringWithFormat:@"%.3f",d].

You can approximately round it with round(d*1000)/1000, but of course this isn't guaranteed to be exact since 1000 isn't a power of 2.

like image 21
tc. Avatar answered Nov 11 '22 06:11

tc.


You can use:

#include <math.h>
:
dbl = round (dbl * 1000.0) / 1000.0;

Just keep in mind that floats and doubles are as close an approximation as the underlying type can provide. It may not be exact.

like image 8
paxdiablo Avatar answered Nov 11 '22 06:11

paxdiablo