Search code examples
cmathintroundinginteger-division

Rounding integer division (instead of truncating)


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"?


Solution

  • int a = 59.0f / 4.0f + 0.5f;
    

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

    Edit: This solution will only work in the simplest of cases. A more robust solution would be:

    unsigned int round_closest(unsigned int dividend, unsigned int divisor)
    {
        return (dividend + (divisor / 2)) / divisor;
    }