guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

scheme (format) question


From: Mark Polesky
Subject: scheme (format) question
Date: Sat, 21 Mar 2009 14:33:32 -0700 (PDT)

;; 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)))



      




reply via email to

[Prev in Thread] Current Thread [Next in Thread]