[racket] Formatting reals

59 views
Skip to first unread message

Pierpaolo Bernardi

unread,
Mar 12, 2013, 11:25:55 PM3/12/13
to users
Hello,

suppose I want to format a real number, with a fixed number of digits
after the comma, rigth-padded in a given width, and I want the sign to
be attached to the digits (i.e. not what ~r does).

This is the usual way of printing reals in a table, and can be done
trivially using standard functions in any other language I can think
of.
In scheme it can be done using srfi/48.

Yet I could find no way of doing this easily using Racket libraries.
Am I missing something?

I want the following:

> (require srfi/48)
> (format "~12,6F" (- pi))
" -3.141593"

The best I could do is:

> (~a (~r (- pi) #:precision 6) #:width 12 #:align 'right)
" -3.141593"

which is a PITA.

(I have used srfi/48 till now, but I was trying to convert to Racket
libraries in an attempt to reduce bloat.)

Cheers
P.
____________________
Racket Users list:
http://lists.racket-lang.org/users

Stephen Chang

unread,
Mar 12, 2013, 11:29:22 PM3/12/13
to Pierpaolo Bernardi, users
Does real->decimal-string do what you want?

Pierpaolo Bernardi

unread,
Mar 12, 2013, 11:58:43 PM3/12/13
to Stephen Chang, users
On Wed, Mar 13, 2013 at 4:29 AM, Stephen Chang <stc...@ccs.neu.edu> wrote:
> Does real->decimal-string do what you want?

yes, except for the width. It can substitute the ~r in

(~a (~r (- pi) #:precision 6) #:width 12 #:align 'right)

but not the ~a.

Srfi/48 still wins in convenience and readability. 8^)

John Clements

unread,
Mar 13, 2013, 12:09:09 PM3/13/13
to Pierpaolo Bernardi, users

On Mar 12, 2013, at 8:25 PM, Pierpaolo Bernardi wrote:

> Hello,
>
> suppose I want to format a real number, with a fixed number of digits
> after the comma, rigth-padded in a given width, and I want the sign to
> be attached to the digits (i.e. not what ~r does).
>
> This is the usual way of printing reals in a table, and can be done
> trivially using standard functions in any other language I can think
> of.
> In scheme it can be done using srfi/48.
>
> Yet I could find no way of doing this easily using Racket libraries.
> Am I missing something?
>
> I want the following:
>
>> (require srfi/48)
>> (format "~12,6F" (- pi))
> " -3.141593"
>
> The best I could do is:
>
>> (~a (~r (- pi) #:precision 6) #:width 12 #:align 'right)
> " -3.141593"
>
> which is a PITA.
>
> (I have used srfi/48 till now, but I was trying to convert to Racket
> libraries in an attempt to reduce bloat.)

+1. I ran into this in some of the rosetta code examples

http://rosettacode.org/wiki/Horizontal_sundial_calculations#Racket

For comparison, the lines in most other languages are far more compact.

John

Michael Wilber

unread,
Mar 13, 2013, 12:39:25 PM3/13/13
to Pierpaolo Bernardi, users
+10! Using just ~r can get close, but ...well...

> (~r (- pi) #:min-width 12 #:precision 6)
"- 3.141593"
Reply all
Reply to author
Forward
0 new messages