tags:

views:

686

answers:

3

I was curious to know how I can round a number to the nearest tenth whole number. For instance, if I had:

int a = 59 / 4;

which would be 14.75 calculated in floating point; how can I store the number as 15 in "a"?

+8  A: 

The standard idiom for integer rounding up is:

int a = (59 + (4 - 1)) / 4;

You add the divisor minus one to the dividend.

Jonathan Leffler
What if you want to perform a mathematical round (14.75 to 15, 14.25 to 14)?
Chris Lutz
Ugh...then you have to think...add (n - 1) / 2, more or less. For n == 4, you want x % n ∈ { 0, 1 } to round down, and x % n ∈ { 2, 3 } to round up. So, you need to add 2, which is n / 2. For n == 5, you want x % n ∈ { 0, 1, 2 } to round down, and x % n ∈ { 3, 4 } to round up, so you need to add 2 again...hence: `int i = (x + (n / 2)) / n;`?
Jonathan Leffler
+4  A: 
int a = 59.0f / 4.0f + 0.5f;

This only works when assigning to an int as it discards anything after the '.'

0xC0DEFACE
Thanks this solution worked perfectly for me!
Dave
Note that this is FLOATING pointer solution. I recommend that you use integer operation for many reasons.
Yousf
What problems? I've used this before and have never encountered a problem.
0xC0DEFACE
+3  A: 

As written, you're performing integer arithmetic, which automatically just truncates any decimal results. To perform floating point arithmetic, either change the constants to be floating point values:

int a = round(59.0 / 4);

Or cast them to a float or other floating point type:

int a = round((float)59 / 4);

Either way, you need to do the final rounding with the round() function in the math.h header, so be sure to #include <math.h>.

Chris Lutz