racket-sprintf
| (require racket-sprintf) | package: racket-sprintf |
The racket-sprintf package provides sprintf and sprintf*, two small C-style string formatting procedures. The format language deliberately supports only a useful subset of C printf. The result is always a string; output is not written to a port.
1 Procedures
2 Format syntax
A conversion has this form:
%[flag][width][.precision][length]conversion |
The supported conversion characters are s, d, f, x, and %. %s formats a string. %d formats a decimal number. %f formats a number using the requested precision. %x formats a number in base 16. %% represents a literal percent sign.
The optional - flag left-aligns a value within its field. Without -, a value with a field width is right-aligned. For numeric conversions, the optional 0 flag pads on the left with zeroes.
A width specifies the minimum field width. For example:
(sprintf "%10s" "Abc") ; => " Abc" |
(sprintf "%-10s" "Abc") ; => "Abc " |
(sprintf "%05d" 42) ; => "00042" |
(sprintf "%-5d" 42) ; => "42 " |
For %s, precision specifies the maximum number of characters taken from the string. Truncation happens before field-width padding. Consequently:
(sprintf "%.5s" "abcdefgh") ; => "abcde" |
(sprintf "%10.5s" "abcdefgh") ; => " abcde" |
(sprintf "%-10.5s" "abcdefgh") ; => "abcde " |
For numeric conversions other than %d, precision is passed to ~r as the number of digits after the decimal point. Decimal integer conversion %d always uses integer-style precision zero.
3 Dynamic width and precision
A width or precision can be written as *. Its value is then consumed from the argument list before the value being formatted. For example:
(sprintf "%*.*f" 8 3 1.23456) |
Here 8 supplies the field width, 3 supplies the precision, and 1.23456 is the value. A dynamic width or precision must be numeric.
4 Length modifier
One or more l characters are accepted before the conversion character for compatibility with existing format strings, but currently have no effect on the result.
5 Type rules
The %s conversion requires a string. The numeric conversions require a number. The implementation intentionally reports a type mismatch instead of silently coercing the value.
6 Examples
(sprintf "%-12s %5d" "items" 42) (sprintf "%08x" 255) (sprintf "%-10.4s" "abcdefgh") (sprintf* "%s = %d" (list "answer" 42))
The implementation uses ~a and ~r from racket/format for the final field formatting.