A formula for rounding number

A formula for rounding numbers

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:

Rounded = n m × m , where n is the number to round, and m 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:

Floor = n m × m , Ceiling = n m × 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:

  1. number is the number you want to round.
  2. 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.
  3. 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:


Leave a Reply

Your email address will not be published.

For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

I agree to these terms.