std.fmt
API summary (generated from the Beans source by npm run coverage): 7 package functions.
std.fmt turns numbers into text in the shapes you often need: hexadecimal,
binary, grouped digits, padded columns, and fixed decimal places. Three functions
are written in Beans at
stdlib/std/fmt/fmt.b;
the other four are native and typed in the compiler, so their parameters are
positional and carry no names.
import std.fmtBase conversions (Beans source)
Section titled “Base conversions (Beans source)”pub fn hex(value: int) -> stringpub fn binary(value: int) -> stringpub fn group_digits(value: int, separator: string) -> stringhexgives lowercase hex of the 64-bit pattern, with no0xprefix, and"0"for zero. It works on the raw u64 bit pattern, so a negative int shows its two’s complement form.binarygives the base-2 text of the value.group_digitsinsertsseparatorevery three digits from the right, and keeps a leading-for negative numbers.
import std.ioimport std.fmt
fn main() { io.println(fmt.hex(255)) // ff io.println(fmt.binary(6)) // 110 io.println(fmt.group_digits(1234567, ",")) // 1,234,567 io.println(fmt.group_digits(-1000, ",")) // -1,000}Padding (native)
Section titled “Padding (native)”pad_left(string, int) -> stringpad_right(string, int) -> stringThe second argument is the target width. pad_left(s, width) pads s with
spaces on the left; pad_right(s, width) pads on the right. Padding is by byte
width. If the input is already at least width bytes wide, it is returned
unchanged. A huge width panics.
import std.ioimport std.fmt
fn main() { io.println(fmt.pad_left("7", 4)) // " 7" io.println(fmt.pad_right("7", 4)) // "7 "}Decimals (native)
Section titled “Decimals (native)”float(float, int) -> stringdecimal(decimal, int) -> stringThe second argument is the number of decimal places, from 0 to 100. float gives
a fixed number of decimal places. decimal is exact: when it needs to show fewer
places than the value has, it rounds half-even (banker’s rounding); when it needs
more, it zero-pads. For example fmt.decimal(19.995, 2) is "20.00".
import std.ioimport std.fmt
fn main() { io.println(fmt.float(3.14159, 2)) // 3.14 io.println(fmt.decimal(19.995, 2)) // 20.00}See Numbers and decimal for the decimal type
itself.
Format specs in interpolation
Section titled “Format specs in interpolation”String interpolation understands the same width and precision specs, so you often
do not need to call these functions at all. Inside "{ ... }":
| Spec | Meaning |
|---|---|
{x:8} | right-align x in a field 8 wide |
{x:-8} | left-align x in a field 8 wide |
{pi:.2} | two decimal places |
{pi:8.2} | width 8 and two decimal places |
These render the same way as pad_left / pad_right and float above.
import std.io
fn main() { let pi: float = 3.14159 io.println("[{pi:8.2}]") // [ 3.14]}