Most programming languages come with native functions that help us round our numbers, either upwards (i.e. **ceiling** operation), downwards (i.e. **floor** operation), or to the nearest whole (i.e. **round** operation). While this is convenient, we sometimes need a bit more than that — what if — for example — we want to round our numbers to the nearest 0.5, or the nearest 3^{rd}?

There’s actually a simple mathematical formula for that, and it looks like this:

$\mathrm{Rounded\; =}\lfloor \frac{n}{m}\rceil \times m,$ $\mathrm{where}\mathit{n}\phantom{\rule{5px}{0ex}}\mathrm{is\; the\; number\; to\; round,}$ $\mathrm{and}\mathit{m}\phantom{\rule{5px}{0ex}}\mathrm{is\; the\; division\; to\; round\; to.}$**Note:** The ⌊*n*⌉ sign around *n* means round *n* to the nearest whole. By extension, ⌊*n*⌋ means to floor *n*; and ⌈*n*⌉ means to ceiling *n*.

If you’re looking to always round up or down to the nearest division, then replace the round operator with the floor or ceiling operator:

$\mathrm{Floor\; =}\lfloor \frac{n}{m}\rfloor \times m,$ $\mathrm{Ceiling\; =}\lceil \frac{n}{m}\rceil \times m,$If you’re looking to implement this in your code, you’re gonna have to write your own function for it. I’ve included the functions I use below in various languages. These functions all accept the same 3 arguments:

is the number you want to round.**number**

is the division you want to round to, e.g. 21 rounded to the nearest 5 will be 20, and if you round up it will be 25.**nearest**

is a string that accepts “ceil” (round up), “floor” (round down) or “round” (to nearest).**direction**

#### Python

def round_nearest(number, nearest, direction = "round"): import math num = number/nearest if direction == "ceil": return math.ceil(num)*nearest elif direction == "floor": return math.floor(num)*nearest else: return round(num)*nearest

#### C#

public static float RoundNearest(float number, float nearest, string direction = "round") { float num = number/nearest; switch(direction) { default: case "round": return Math.Round(num); case "ceil": return Math.Ceiling(num); case "floor": return Math.Floor(num); } }

Article continues after the advertisement: