Rounding integer division (instead of truncating)

Dave picture Dave · Mar 11, 2010 · Viewed 150.3k times · Source

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

int a = 59 / 4;

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

Answer

Jonathan Leffler picture Jonathan Leffler · Mar 11, 2010

The standard idiom for integer rounding up is:

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

You add the divisor minus one to the dividend.