On Jun 30, 2009, at 10:34 AM, Ramana Kumar wrote:

Does anyone know of a Scheme tool for formatting numbers with the
following (or similar) abilities:
- specify the number of decimal places for decimal notation
- specify whether or not to use exponential notation, and the precision if so
- or, specify the number of significant figures and "auto-format" in
decimal from there

I did it, all by myself!

Revision 1821 has two extra libraries that you can use for parsing
and formatting floating point numbers.  The parser is generic, and
the supplied formatter is basically the one ikarus uses internally.
You can easily make your own formatter to fit some of the criteria
mentioned above.  If there's some missing functionality that you
want added, let me know.  Here is a sample script and its output.
It should be enough to get you started.  If you write a useful
formatter, please share.  (The libraries should run on any R6RS
system)

Aziz,,,

#!r6rs

(import (ikarus) (ikarus flonum-parser) (ikarus flonum-formatter))

(define (silly-format pos? digits expt)
  (format "~a0.~ae~a" (if pos? '+ '-) (list->string digits) expt))

(define (test x)
  (printf "; ~s => ~s or ~s\n"
    x
    (parse-flonum x ikarus-format-flonum values)
    (parse-flonum x silly-format values)))

(test 0.0)
(test 1.0)
(test 12.0)
(test -138472.1)
(test 2397239847893.384723)
(test 5e-324)
(test +inf.0)

; 0.0 => "0.0" or "+0.0e-323"
; 1.0 => "1.0" or "+0.1e1"
; 12.0 => "12.0" or "+0.12e2"
; -138472.1 => "-138472.1" or "-0.1384721e6"
; 2.397239847893385e12 => "2.397239847893385e12" or "+0.2397239847893385e13"
; 5e-324 => "5e-324" or "+0.5e-323"
; +inf.0 => "+inf.0" or "+inf.0"

Reply via email to