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.

2 Responses to “A Simple Algorithm for Rounding to the Nearest Multiple-of-n”

  1. 1
    Johnny Nofat:

    Are suggesting I am fat?

  2. 2
    Bob Lezotte:

    Hi Nathan,
    I was revisiting old code of yours and thought “why not google him?”. I hope you’re doing well. The office has been quiet these days but we’re finally looking at writing BEX2. Your base code for the webservice is still intact and has worked spectacularly over the past 6 years with very few modifications.
    Good to see you’re still writing code. It was a very instructive couple of years for me watching you code.
    Take care of yourself,
    Bob

Leave a Reply