diff --git a/collects/scheme/private/string.ss b/collects/scheme/private/string.ss index 731833332b..0d04dcaeab 100644 --- a/collects/scheme/private/string.ss +++ b/collects/scheme/private/string.ss @@ -12,18 +12,22 @@ (require (for-syntax "stxcase-scheme.ss")) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - (define (real->decimal-string 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)))))) + (unless (exact-nonnegative-integer? digits) + (raise-type-error 'real->decimal-string "exact-nonnegative-integer" n)) + (if (zero? digits) + (number->string (inexact->exact (round n))) + (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 diff --git a/collects/tests/mzscheme/string.ss b/collects/tests/mzscheme/string.ss index 8ace942d04..0948978835 100644 --- a/collects/tests/mzscheme/string.ss +++ b/collects/tests/mzscheme/string.ss @@ -5,6 +5,20 @@ ;; to add when this library is there: (require scheme/string) +(test "0" real->decimal-string 0 0) +(test "0" real->decimal-string 0.0 0) +(test "1" real->decimal-string 0.6 0) +(test "1" real->decimal-string 3/4 0) +(test "1" real->decimal-string 1.2 0) +(test "0" real->decimal-string -0.0 0) ; ! +(test "-1" real->decimal-string -0.6 0) +(test "-1" real->decimal-string -3/4 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.00" real->decimal-string 0.99999999999) +(test "-1.00" real->decimal-string -0.99999999999) + (let ([s (list->string (let loop ([i 0]) (if (= i 256)