[gambit-list] Error when loading/running

Marc Feeley feeley at iro.umontreal.ca
Mon Oct 31 13:19:03 EDT 2011


On 2011-10-31, at 12:27 PM, Steve Graham wrote:

> Thanks, all.
> 
> I noticed that I "print" will not handle decimals properly.  I've googled for formatted output for Gambit and Scheme and haven't found any info on this that applies to Gambit.  Have also looked in the latest version of The Scheme Programming Language and it also does not deal with formatted decimals, although it does mention printf, which Gambit seems to lack.
> 
> Any comments on how to print formatted decimals?
> 
> Thanks again, Steve

I've used this function in the past.

Marc

(define (fmt num #!optional (d 6) (w 0))

  ;; Formats a number to a string, where d is the number of decimals
  ;; and w is the total width.

  (let ((n (floor (inexact->exact (round (* (abs num) (expt 10 d)))))))
    (let ((i (quotient n (expt 10 d)))
          (f (modulo n (expt 10 d))))
      (let ((si (string-append
                  (if (< num 0) "-" "")
                  (if (and (= i 0) (> d 0)) "" (number->string i 10))))
            (sf (number->string (+ f (expt 10 d)) 10)))
        (if (> d 0)
          (string-set! sf 0 #\.)
          (set! sf ""))
        (let ((lsi (string-length si))
              (lsf (string-length sf)))
          (let ((blanks (- w (+ lsi lsf))))
            (string-append (make-string (max blanks 0) #\space) si sf)))))))

(print (fmt 3.1415926 3)) ;; prints 3.142




More information about the Gambit-list mailing list