# Is this how to round?

• 10-25-2011
george7378
Is this how to round?
Hi everyone,

I was just wondering - is this a valid way to round to the nearest integer in C++?

Code:

```double round(double x) { if(x<0){return ceil(x-0.5);} else if(x>0){return floor(x+0.5);} else {return(x=0);} }```
Thanks a lot.
• 10-25-2011
whiteflags
• 10-25-2011
george7378
I tried it and it worked for the numbers I put in, but I didn't know if there was anything I had missed. I guess it's ok!
• 10-25-2011
King Mir
Remember to test the infinities and NaN. Cause right now, NaN will give the wrong answer.
• 10-25-2011
iMalc
It's valid, but overkill.
floor rounds towards minus infinity and ceil rounds towards positive infinity. So they both have the same behaviour either side of zero. This means that you don't need to use both. There's also no reason to have a special case for zero because the floor of zero plus 0.5 is still zero. So all you need is:
Code:

```double round(double x) {     return floor(x+0.5); }```
• 10-25-2011
george7378
Thanks for the help - I found iMalc's suggestion in other places, but people seemed to be saying that it didn't work for negatives. On second thought, it does, doesn't it?

Thanks!
• 10-25-2011
brewbuck
Quote:

Originally Posted by george7378
Thanks for the help - I found iMalc's suggestion in other places, but people seemed to be saying that it didn't work for negatives. On second thought, it does, doesn't it?

Thanks!

It depends whether you want the result to be a double or an integer. It is common to round by casting to int like this:

Code:

```double x = ...; int rounded = (int)(x + 0.5);```
The above does NOT do the right thing if x is negative, because integer truncation goes toward zero, it's not like floor()