You want to print a number with a specified a format.
The generic printing functions,
display,
write,
format, and so on don't give you much control over the formatting of numbers. There are few ways to print numbers in custom formats.
SRFI-48 provides some basic numeric formatting capability with the
~F specifier. The
~F specifier should be preceded by at least one number, for example
~4F, which specifies the minimum width of its output. Output smaller than the minimum will have spaces added to the front of the string to take it to the minimum. If you follow the width with a comma and another number, for example
~4,4F that number determines how many places are printed after the decimal. Here are examples showing both forms:
> (require (lib "48.ss" "srfi"))
> (format "~4F" 10)
" 10"
> (format "~4,4F" (sqrt 2))
"1.4142"
An alternative formatting procedure is provided by
real->decimal-string in
(lib "string.ss"). This function prints a number with a fixed number of digits after the decimal point to a string. By default numbers are printed with two digits after the decimal but you can control this. Here are some examples:
> (require (lib "string.ss"))
> (real->decimal-string 100)
"100.00"
> (real->decimal-string 100.001)
"100.00"
> (real->decimal-string 3.1415927 4)
"3.1416"
Finally, here is a procedure to print number in scientific format:
(require (lib "string.ss"))
(define real->scientific-string
(case-lambda
[(x)
(real->scientific-string x 2)]
[(x digits-after-decimal-k)
(let* ([sign (if (negative? x) -1 +1)]
[x (* sign (inexact->exact x))]
[e-orig (inexact->exact (floor (/ (log x) (log 10))))]
[e (inexact->exact
(- (floor (/ (log x) (log 10)))))]
[x-normalized (* (inexact->exact x) (expt 10 e))])
(format "~a~ae~a"
(if (negative? sign) "-" "")
(if (zero? digits-after-decimal-k)
(round x-normalized)
(real->decimal-string
(exact->inexact x-normalized)
digits-after-decimal-k))
e-orig))]))
Here are some examples of its use:
> (real->scientific-string 100)
"1.00e2"
> (real->scientific-string 100.1)
"1.00e2"
> (real->scientific-string 100.1 4)
"1.0010e2"
Adapted from a plt-scheme post
http://list.cs.brown.edu/pipermail/plt-scheme/2006-December/015621.html
--
NoelWelsh - 05 May 2007