Formatting negative numbers using `~r`

I was trying to format numbers using ~r to align them in a table, and noticed an unexpected, for me at least, result for negative numbers: the minus sign is put in front of the padding:

> (~r (- pi) #:precision 2 #:min-width 10)
"-      3.14"

I suppose this makes sense if the pad-string is "0", but does not make sense for any other pad-string:

> (~r (- pi) #:precision 2 #:min-width 10 #:pad-string "0")
"-0000003.14"
> (~r (- pi) #:precision 2 #:min-width 10 #:pad-string "#")
"-######3.14"

I can always combine ~a and ~r to get the desired result, but I am wondering if this is a defect/omission, or is it a convention I am not aware of?

> (~a (~r (- pi) #:precision 2) #:min-width 10 #:align 'right)
"     -3.14"

Thanks,
Alex.

2 Likes

From the documentation for ~r's #:pad-string option:

The padding is placed between the sign and the normal digits of x.

And the default padding is a space, so this behavior, while not what I'd expect to see, is what's documented. Another oddity is that #:min-width doesn't count the sign as part of the length; your strings are 11 characters long, not 10.

I ported SLIB's implementation of the Common Lisp format to Racket as the slib-format package and use that for most text formatting, as it has a ton of options beyond the formatting functions that come with Racket and tends to Just Work:

> (require slib/format)
> (format #f "~10,2F" (- pi))
"     -3.14"
> (format #f "~10,2,,,'#F" (- pi))
"#####-3.14"