What is the function for "round n to the nearest m"? Where $n \in \mathbb{R}$ and $m \in \mathbb{R}$, what is the function $f(n, m)$ that can achieve rounding behavior of money where the smallest denomination is not an power of ten?
For instance, if a 5¢ coin is the smallest denomination (like in Canada):


*

*$f(1.02, 0.05) = 1.00$

*$f(1.03, 0.05) = 1.05$

*$f(1.29, 0.05) = 1.30$

*$f(1.30, 0.05) = 1.30$


Or if $20 is the cutoff:


*

*$f(9.99, 20) = 0$

*$f(10, 20) = 20$

*$f(39.99, 20) = 40$

*$f(40, 20) = 40$

 A: 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 $127$ 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.$$
A: 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.
A: 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.
