change real->decimal-string (PR 9285)

svn: r9210
This commit is contained in:
Matthew Flatt 2008-04-08 21:56:29 +00:00
parent 021d4d7527
commit cb3fdd8fc5
2 changed files with 26 additions and 22 deletions

View File

@ -15,18 +15,21 @@
(define (real->decimal-string n [digits 2]) (define (real->decimal-string n [digits 2])
(unless (exact-nonnegative-integer? digits) (unless (exact-nonnegative-integer? digits)
(raise-type-error 'real->decimal-string "exact-nonnegative-integer" n)) (raise-type-error 'real->decimal-string "exact-nonnegative-integer" n))
(if (zero? digits) (let* ([e (expt 10 digits)]
(number->string (inexact->exact (round n))) [num (round (abs (* e (inexact->exact n))))])
(let* ([e (expt 10 digits)] (format "~a~a.~a"
[num (round (abs (* e (inexact->exact n))))]) (if (or (negative? n)
(format "~a~a.~a" (equal? n -0.0))
(if (negative? n) "-" "") "-"
(quotient num e) "")
(let ([s (number->string (remainder num e))]) (quotient num e)
(if (= (string-length s) digits) (if (zero? digits)
s ""
(string-append (make-string (- digits (string-length s)) #\0) (let ([s (number->string (remainder num e))])
s))))))) (if (= (string-length s) digits)
s
(string-append (make-string (- digits (string-length s)) #\0)
s)))))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Regexp helpers ;; Regexp helpers

View File

@ -5,20 +5,21 @@
;; to add when this library is there: (require scheme/string) ;; to add when this library is there: (require scheme/string)
(test "0" real->decimal-string 0 0) (test "0." real->decimal-string 0 0)
(test "0" real->decimal-string 0.0 0) (test "0." real->decimal-string 0.0 0)
(test "1" real->decimal-string 0.6 0) (test "1." real->decimal-string 0.6 0)
(test "1" real->decimal-string 3/4 0) (test "1." real->decimal-string 3/4 0)
(test "1" real->decimal-string 1.2 0) (test "1." real->decimal-string 1.2 0)
(test "0" real->decimal-string -0.0 0) ; note this! (test "-0." real->decimal-string -0.0 0) ; note this!
(test "0.00" real->decimal-string -0.0) ; same here... (test "-0.00" real->decimal-string -0.0) ; same here...
(test "-1" real->decimal-string -0.6 0) (test "-1." real->decimal-string -0.6 0)
(test "-1" real->decimal-string -3/4 0) (test "-1." real->decimal-string -3/4 0)
(test "-1" real->decimal-string -1.2 0) (test "-1." real->decimal-string -1.2 0)
(test "1.20" real->decimal-string 1.2) (test "1.20" real->decimal-string 1.2)
(test "-1.20" real->decimal-string -1.2) (test "-1.20" real->decimal-string -1.2)
(test "1.00" real->decimal-string 0.99999999999) (test "1.00" real->decimal-string 0.99999999999)
(test "-1.00" real->decimal-string -0.99999999999) (test "-1.00" real->decimal-string -0.99999999999)
(test "1999999999999999859514578049071102439861518336.00" real->decimal-string 2e45)
(let ([s (list->string (let ([s (list->string
(let loop ([i 0]) (let loop ([i 0])