Ekinoderm
 

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.

One Response to “A Simple Algorithm for Rounding to the Nearest Multiple-of-n”

  1. 1
    Johnny Nofat:

    Are suggesting I am fat?

Leave a Reply

Search

Cool Jobs

Blogroll

Meta