fixed pr9285, added tests
svn: r9197
This commit is contained in:
parent
2888a16d0e
commit
26b283b953
|
@ -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
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue
Block a user