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 3rd?
There’s actually a simple mathematical formula for that, and it looks like this:
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:
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:
number
is the number you want to round.nearest
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.direction
is a string that accepts “ceil” (round up), “floor” (round down) or “round” (to nearest).
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: