Extra Fox – A blog by Christopher Taylor

Rounding Doubles to Integers in C#

Posted in Uncategorized by extrafox on August 31, 2006

I looked all over the place in the C# libraries for a simple method to round a Double to an Integer. I finally gave up and decided that such a thing may not actually exist. So, I went out on the net to find someone else’s implementation, but I didn’t like the one that I did find. So, here is my take on the problem…

public static long Round(double d) {
double ceilD = (double)Math.Ceiling(d);
double floorD = (double)Math.Floor(d);

// is the original double closer to the ceiling?
return ((ceilD - d) < (d - floorD)) ?
(long)ceilD : (long)floorD;

I’m not sure about efficiency, but there is a certain elegance to this approach. Hope it is useful for someone.

UPDATE: don’t know how I missed this one… [abstracttb.com]


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 )

Google+ photo

You are commenting using your Google+ 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

%d bloggers like this: