[plt-scheme] best way to printf "%.2f" ?

From: gknauth at sunlink.net (gknauth at sunlink.net)
Date: Sat Dec 9 15:17:43 EST 2006

This is perfect--thank you Jens Axel!  --Geoff

-----Original Message-----
Wrote Jens Axel Søgaard <jensaxel at soegaard.net>:

Try this, but test it first! Number formating is surprisingly tricky.

(define real->scientific-string
   (case-lambda
     [(x)
      (real->scientific x 2)]
     [(x digits-after-decimal-k)
      (let* ([sign         (if (negative? x) -1 +1)]
             [x            (* sign (inexact->exact x))]
             [e-orig       (inexact->exact (floor (/ (log x) (log 10))))]
             [e            (inexact->exact
                               (- (floor (/ (log x) (log 10)))))]
             [x-normalized (* (inexact->exact x) (expt 10 e))])
            (format "~a~ae~a"
                    (if (negative? sign) "-" "")
                    (if (zero? digits-after-decimal-k)
                        (round x-normalized)
                        (real->decimal-string
                            (exact->inexact x-normalized)
                             digits-after-decimal-k))
                    e-orig))]))



Posted on the users mailing list.