What is the function for "round n to the nearest m"?

Are you familiar with the floor function? For $x \in\mathbb{R}$, $\lfloor x\rfloor$ is the greatest integer less than or equal to $x$. That is, there exists an integer $n$ such that $n \leq x <n+1$, and we define $\lfloor x \rfloor =n$. So the floor function rounds to integers, though not to the nearest integer, as, say, $\lfloor 0.9\rfloor = 0$. We can remedy this by taking $f(x)=\lfloor x+0.5\rfloor$. Then $f$ rounds $x$ to the nearest integer to $x$ (rounding $0.5$ up to $1$, etc.).

If you want to round by larger increments, you can scale the input before and after putting it into the floor function. For example, say we want to round $123$ to the tens digit. Then we first have to scale $127$ down by a factor of $10$, round to the ones digit, and scale it back up: $$\left\lfloor \frac{127}{10}\right\rfloor\cdot 10=\lfloor 12.7\rfloor\cdot 10=12\cdot 10=120.$$ If we want to round to the nearest ten, then again we need to add $0.5$ inside the floor: $$\left\lfloor \frac{127}{10}+0.5\right\rfloor \cdot 10=\lfloor 12.7+0.5\rfloor \cdot 10=\lfloor 13.2\rfloor \cdot 10=13\cdot 10=130.$$

Hopefully you see that the formula you want is $$f(n,m)=\left\lfloor \frac{n}{m}+0.5\right\rfloor \cdot m.$$


Well, as with all things in math, if you need such a function, there's nothing stopping you from saying $f(n,m)$ is $n$ rounded to the nearest $m$, where the higher option is chosen for $n$ precisely between two consecutive multiples of $m$. If you need this a lot, it's easier to read than having a formula each time you invoke this.

However, one can build this out of the floor function, where $\lfloor x\rfloor$ is defined as the greatest integer less than or equal to $x$. So $\lfloor .5 \rfloor = 0$ for instance. Then, you have $$f(m,n)=m\left\lfloor \frac{n}m+\frac{1}2\right\rfloor.$$ This just works by taking the function $\lfloor x + 1/2\rfloor$, which rounds to the nearest integer (with half-integers rounding up), and appropriately scaling.


You didn't indicate what you wanted to do with negative values. The below rounds toward the nearest denominated value. There are other choices.

Let $a$ be the amount and $g$ be the minimum denomination. Your $f$ is $$ f(a,g) = g\left\lfloor \frac{a}{g} + \frac{1}{2} \right\rfloor $$ where the "$\lfloor$" and "$\rfloor$" indicate the floor function.