Floating Point Rounding
January 8, 2013
This is easy enough:
(define (round f n)
(/ (truncate (+ (* f (expt 10 n)) 0.5)) (expt 10 n)))
(expt 10 n) returns 1000 when n is 3, 100 when n is 2, 1 when n is 0, and 1/10 when n is -1. This number is first multiplied by f and then divided into the result, so the output has the same order as the input. In between the multiplication and the division, 0.5 is added, then the result of the addition is truncated, which has the desired rounding effect. There is no need for extra credit here; the function works perfectly well for both positive and negative n.
You can run the program at http://programmingpraxis.codepad.org/AF35jtp1.
Pages: 1 2