C Round Function


It’s really weird that the C math library (math.h) doesn’t support the round function. It only includes the floor function which rounds down a float to an integer (can also be done by implicit or explicit casting) and the ceil function which rounds the value up.

For example,

int x;

x = floor(1.2);   //  x is set to 1
x = floor(1.8);   //  x is set to 1
x = (int)1.8;     //  x is set to 1 (Explicit Narrowing Conversion)
x = 1.8;          //  x is set to 1 (Implicit Narrowing Conversion)
x = ceil(1.2);    //  x is set to 2
x = ceil(1.8);    //  x is set to 2

The round function is supposed to round the float value to the nearest integer.

x = round(1.2);    //  x is set to 1
x = round(1.8);    //  x is set to 2

This can be done adding a 0.5 to the value and then truncating it.

x = (int)(1.2 + 0.5);  //  x is set to 1
x = (int)(1.8 + 0.5);  //  x is set to 2

We also have to take negative values into consideration by adding -0.5 and then truncating.

x = (int)(-1.2 - 0.5);  //  x is set to -1
x = (int)(-1.8 - 0.5);  //  x is set to -2

Thus, here is the resulting C function:

int round(double number)
{
    return (number >= 0) ? (int)(number + 0.5) : (int)(number - 0.5);
}

Note that you might want to use long rather than int to include support for larger numbers and avoid integer overflow.

That’s it, pretty much primitive, but fun!

Enjoy!
Ali B

    • davidhilton
    • February 28th, 2008

    Two other options; just use floor(x+.5) or make a macro- #define round(X) floor((X)+.5)

    • alibad
    • February 28th, 2008

    You are right. floor(x+.5) is just the same as (int)(x+.5). But you forgot to take negative values into consideration.

  1. Interestingly, I even nedumala about it …

    • Cork
    • September 5th, 2009

    Very useful – thanks. Also, I like davidhilton’s idea of turning your function into a macro.

    • atrujillo
    • February 16th, 2010

    I like to see the code applied to rounding of number to the nearest decimal place or to adjustable decimal places.

      • alibad
      • February 16th, 2010

      Someone has already shared this function in the comments to the CodeProject copy of this post. Enjoy :)

      EX:
      Round(1.234,2) = 1.23
      Round(1.234,0) = 1.0
      Round(123.4,-1) = 120.0

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.