Jump to content

Rounding functions

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 24.69.255.204 (talk) at 03:10, 11 December 2002. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

To round a fractional number to the nearest integer (in C):

int round(double d) { return (int)(d + 0.5); }

The above, however, rounds negative numbers unintuitively, e.g., -2.7 becomes -2 instead of -3. At the expense of more computation, one can use:

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