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$
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.$$