[plt-scheme] Printing

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Sat Oct 15 16:24:10 EDT 2005

Joe Marshall wrote:
> As it happens, I wanted to do this last week.
> Here is my solution:
> 
> (define (format-float float digits)
>   (let* ((numerals (number->string (round (* (inexact->exact float)
> (expt 10 digits)))))
>          (length   (string-length numerals))
>          (dot      (- length digits)))
>     (string-append
> 
>      (if (< dot 0) "0" (substring numerals 0 dot))
>      "."
>      (if (< dot 0)
>          (string-append (make-string (- dot) #\0) numerals)
>          (substring numerals dot length)))))

I see that you use round, which rounds to even. Which makes
sense in numerical calculations, where you hope the rounding
errors to the two sides will cancel - but is it normal to
use for formatting?

Perhaps the formating section in R3RS should be revived?

   > (format-float -0.5 0)
   "0."
   > (format-float -0.05 1)
   "-.1"
   > (format-float -0.005 2)
   ".-1"                           ; ?
   > (format-float -0.0005 3)
   "0.0-1"
   > (format-float -0.0005 4)
   "0.00-5"

-- 
Jens Axel Søgaard




Posted on the users mailing list.