A Simple Algorithm for Rounding to the Nearest Multiple-of-n
Normally, I wouldn’t make such a brief post, but I’ve encountered (several times) some very bizarre and complicated algorithms to round to the nearest multiple-of-n (where n is 5 or 7 or whatever). Say, for example, that you’re pricing your product for an overseas military base, and, as we know, overseas military bases don’t use pennies, so all prices must be multiples of 5. So, you want to have your program round the price off to the nearest multiple-of-5. It’s really very simple:
public static int RoundToNearestMultipleOfN(double val, int n) { return (int)Math.Round((val / n)) * n; }
So seriously, don’t get all bent out of shape.

February 3rd, 2009 at 1:46 pm
Are suggesting I am fat?