-
Rounding off a double
Does anyone have any sample code on how to round off a double to a whole number (nearest one)? Say for example rounding 2.12 to 3 and 2.7 to 3?
Any help would be appreciated. I am learning C and have not found
this info on the net so far (though it might be out there).
Thanks.
-
ceil() from math.h will do exactly what you give as examples. However, I believe what you actually want is
Code:
double round(double x)
{
return floor(x + 0.5);
}
That will round any number UP that ends with .5 or higher, and down if it's ending with .4999999 or lower. So 2.12 turns into 2.0, 2.7 turns into 3.0
--
Mats
-
Although, if you're including math.h, there's a perfectly good round() function already there.
-
I think round() is C99 only - and so may not be available.
Which is a good reason to call it "my_round()", or something similar, to avoid potential name collisions.
gg