added real->decimal-string (one piece of a real formatter)

svn: r4685

original commit: 58191912c6f0e292e60cb7d537c2508fe5bae71f
This commit is contained in:
Matthew Flatt 2006-10-26 06:55:29 +00:00
parent d961bfaf01
commit 0ee9f22efd

View File

@ -6,6 +6,7 @@
read-from-string read-from-string
read-from-string-all read-from-string-all
expr->string expr->string
real->decimal-string
regexp-quote regexp-quote
regexp-replace-quote regexp-replace-quote
regexp-match* regexp-match*
@ -108,6 +109,21 @@
(write v port) (write v port)
(get-output-string port)))) (get-output-string port))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define real->decimal-string
(opt-lambda (n [digits 2])
(let* ([e (expt 10 digits)]
[num (round (abs (* e (inexact->exact n))))])
(format "~a~a.~a"
(if (negative? n) "-" "")
(quotient num e)
(let ([s (number->string (remainder num e))])
(if (= (string-length s) digits)
s
(string-append (make-string (- digits (string-length s)) #\0)
s)))))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Regexp helpers ;; Regexp helpers