Hi everyone,

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

Thanks a lot.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);}

}

Printable View

- 10-25-2011george7378Is 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);}

}

- 10-25-2011whiteflags
Test your function and see if the answer is right.:rolleyes:

- 10-25-2011george7378
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-2011King Mir
Remember to test the infinities and NaN. Cause right now, NaN will give the wrong answer.

- 10-25-2011iMalc
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-2011george7378
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-2011brewbuck
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);