7

How do you get a printf %6.2f in scheme or racket, as you would in C?

Right now all I have is printf "The area of the disk is ~s\n" ( - d1 d2), but I can't format the output to a specific floating point format.

Thanks

Leistungsabfall
  • 6,368
  • 7
  • 33
  • 41
user3161399
  • 253
  • 2
  • 6

2 Answers2

6

To get a behavior closer to C's printf() function use the format procedure provided by SRFI-48, like this:

(require srfi/48)
(format "The area of the disk is ~6,2F~%" (- d1 d2))

A more verbose alternative would be to use Racket's built-in ~r procedure, as suggested by @stchang:

(string-append
 "The area of the disk is "
 (~r (- d1 d2) #:min-width 6 #:precision '(= 2))
 "\n")
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    And in [tag:Scheme] you just include `(srfi :48)` amongst the imports instead of the `require` form. – Sylwester Sep 26 '14 at 20:52
  • 2
    Maybe I should start a separate question about this but, how is "srfi/48" a good name? In other languages you'd require "text" or "formatting". – Eldritch Conundrum May 30 '15 at 16:19
4

Racket has ~r.

You'll probably want to provide #:min-width and #:precision arguments.

stchang
  • 2,555
  • 15
  • 17