printf ( format-string -- quot ) (original) (raw)
Vocabulary
formatting
Inputs
Outputs
None
Word description
Writes the arguments (specified on the stack) formatted according to the format string.
Several format specifications exist for handling arguments of different types, and specifying attributes for the result string, including such things as maximum width, padding, and decimals.
%% | Single % | |
---|---|---|
%P.Ds | String | string |
%P.DS | String uppercase | string |
%P.Du | Unparsed | object |
%c | Character | char |
%C | Character uppercase | char |
%LPd | Integer decimal (base 10) | real |
%LPx | Integer hexadecimal (base 16) | real |
%LPX | Integer hexadecimal uppercase (base 16) | real |
%LPo | Integer octal (base 8) | real |
%LPb | Integer binary (base 2) | real |
%LP.De | Scientific (base 10) | real |
%LP.DE | Scientific uppercase (base 10) | real |
%LP.Df | Fixed (base 10) | real |
%[%?, %] | Sequence | sequence |
%[%?: %? %] | Assocs | assoc |
Leading (L) is used to optionally prefix a plus sign ("+") or space (" ") if the formatted number is positive.
Padding (P) is used to optionally specify the minimum width of the result string, the padding character, and the alignment. By default, the padding character defaults to a space and the alignment defaults to right-aligned. For example:
• | %5s formats a string padding with spaces up to 5 characters wide. |
---|---|
• | %03d formats an integer padding with zeros up to 3 characters wide. |
• | %'#10f formats a float padding with # up to 10 characters wide. |
• | %-10d formats an integer to 10 characters wide and left-aligns. |
Digits (D) is used to optionally specify the maximum digits in the result string. For example:
• | %.3s formats a string to truncate at 3 characters (from the left). |
---|---|
• | %.10f formats a float to pad-tail with zeros up to 10 digits beyond the decimal point. |
• | %.5E formats a float into scientific notation with zeros up to 5 digits beyond the decimal point, but before the exponent. |
Examples
USING: formatting ; 123 "%05d" printf
00123
USING: formatting ; 0xff "%04X" printf
00FF
USING: formatting ; 12 "%b" printf
1100
USING: formatting ; 1.23456789 "%.3f" printf
1.235
USING: formatting ; 12 "%'#4d" printf
##12
USING: formatting ; 1234 "%+d\n" printf -1234 "%+d\n" printf 1234 "% d\n" printf
+1234 -1234 1234
USING: formatting ; { 1 2 3 } "%[%d, %]" printf
{ 1, 2, 3 }
USING: formatting ; H{ { 1 2 } { 3 4 } } "%[%d: %d %]" printf
{ 1:2, 3:4 }
USING: calendar formatting ; 3 years "%u" printf
T{ duration { year 3 } }
Definition