Mark Polesky:
;; Hi. ;; ;; How can I change the following code so that ;; it returns "2 0.25 0.3333"? That is: return ;; integers without decimal point, otherwise ;; round to as many decimal places as needed, ;; but not more than 4. (let ((a 2.0) (b 1/4) (c 1/3)) (format #t "~&~a ~a ~a" a b c)) ;; After some experimenting, I found the ;; following solution, but I'd rather not have ;; to deal with all the incessant quasiquote ;; and unquote stuff. Is there a more elegant ;; solution? ;; ;; Thanks in advance. ;; - Mark (define (set-precision n) (let* ((max-decimals 4) (k (expt 10.0 max-decimals))) (if (number? n) (if (integer? n) (inexact->exact n) (/ (round (* n k)) k)) n))) (define (my-format bool string list-of-nums) (apply format bool string (map set-precision list-of-nums))) (let ((a 2.0) (b 1/4) (c 1/3)) (my-format #t "~&~a ~a ~a" `(,a ,b ,c)))
Yes: (let ((a 2.0) (b 1/4) (c 1/3)) (my-format #t "~&~a ~a ~a" (list a b c))) But better: (define (my-format bool string . list-of-nums) (apply format bool string (map set-precision list-of-nums))) (let ((a 2.0) (b 1/4) (c 1/3)) (my-format #t "~&~a ~a ~a" a b c)) I would also think that 'format' has an option to do this directly without calling 'set-precision', but I don't know...