I\'ve got a float value from an accelerometer which looks like this:
-3.04299553323
I\'d like to get -3.04 for example. Is there an easy way for rounding tha
Multiply it by 100, (round up/down to nearest integer if necessary), take the integer portion, then divide by 100 again
Applies for any number decimals places, multiply/divide by 10^(no. of decimals).
You should only ever do this while formatting a number for display to the end user, because there is no guarantee that
float rounded = roundf(orig * 100) / 100.0;
or similar will return an exact answer.
Indeed, in general, it won't. For instance consider
float f = 123456.3;
float r = roundf(f * 100) / 100.0;
printf("%.2f, %.10f\n", r, r);
which outputs
123456.30, 123456.2968750000
Oops!
Using double
rather than float
helps, but even so, if we change the code a little, you can see that it doesn't really solve the problem:
double f = 123456.3;
double r = round(f * 100) / 100.0;
printf("%.2f, %.20f\n", r, r);
Again, we get
123456.30, 123456.30000000000291038305
which shows quite clearly that it isn't exactly rounded.
Anyway, the moral of the story is that doing things like round(f * 100) / 100.0
only rounds approximately. It might be good enough in some cases, but you do need to keep in mind that the result is not really rounded.
If you want something better, you'll need to use decimal arithmetic instead. You can either do this by keeping your values as integers (e.g. for currency values, keep them in pence or cents instead of pounds or dollars), or by using one of the various decimal floating point packages you can find on Wikipedia's Decimal Floating Point page.
I just post my answer to this question cause it was the only way for me to get this working quickly as I merged two of the given answers to display a rounded float value to the user in an iPad app:
NSString *roundedAmount = [NSString stringWithFormat:@"%.2f", round ((floatValue / 1024) * 100.0) / 100.0];
I know this is old post but just in case someone else is looking for a quick Two step option.
float old = -3.04299553323;
float new = [[NSString stringWithFormat:@"%.2f",old]floatValue];
Result = -3.04
The @"%.2f" will round to two decimal places. If you want three decimal places put @"%.3f" and so on.
Hope this helps!