Round to Nearest

I recently had to write some code to round a value to something other than the nearest integer, e.g. rounding a measurement to the nearest 0.5 or 0.1 unit.


roundto
To figure out how to do it, suppose we want to round to the nearest multiple of, say, 5.


Scale the number line from 0, 5, 10, ... to 0, 1, 2, ...


Round.


Then scale from 0, 1, 2... back to 0, 5, 10...

Extension to values other than 5 is straightforward.

The Lisp code:

(defun round-to (n m)
(if (or (null m) (zerop m))
n
(* (round (/ n (float m))) (float m))))


Comments