Friday, June 15, 2007

Rounding

In the .NET Framework, the System.Math class has methods for Ceiling, Floor, Round, and Truncate. Round has an overload for specifying the number of decimal places to round to but it doesn't support other intervals, for example: rounding to the nearest five cents.

The mathematics involved for supporting other intervals is quite simple when you know it but getting there and verifying it can take a few moments. Here is the general solution to save time next time I need it, or if someone else is looking for the same thing:

decimal offset = 0.05M;        // interval we are rounding to (5 cents)
decimal value = 1.23M;         // value to be rounded
decimal temp = value / offset;
temp = MyRoundToInteger(temp); // toward zero or banker's rounding function
decimal result = temp * offset;

You can exchange MyRoundToInteger for any of the afore mentioned Math class methods or even one of your own custom rounding techniques, as long as it rounds to zero decimal places

Friday, June 15, 2007 4:00:12 PM (Cen. Australia Standard Time, UTC+09:30)
If you're only dealing with integers, another easy method is simply to add the half of the offset then round down. Casting to an integer automatically drops the decimal, so for example:

Rounding to the nearest "1":

int result = (int)(value + 0.5);

Rounding to the nearest 100:

int result = (int)(value + 50);

If "value" is 0.7, for example, adding 0.5 bumps it to 1.2, then rounding down drops the 0.2 - works for any integer.
Comments are closed.