[plt-scheme] Printing
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