Skip to content

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.fmt
pub fn hex(value: int) -> string
pub fn binary(value: int) -> string
pub fn group_digits(value: int, separator: string) -> string
  • hex gives lowercase hex of the 64-bit pattern, with no 0x prefix, and "0" for zero. It works on the raw u64 bit pattern, so a negative int shows its two’s complement form.
  • binary gives the base-2 text of the value.
  • group_digits inserts separator every three digits from the right, and keeps a leading - for negative numbers.
import std.io
import 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
}
pad_left(string, int) -> string
pad_right(string, int) -> string

The 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.io
import std.fmt
fn main() {
io.println(fmt.pad_left("7", 4)) // " 7"
io.println(fmt.pad_right("7", 4)) // "7 "
}
float(float, int) -> string
decimal(decimal, int) -> string

The 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.io
import 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.

String interpolation understands the same width and precision specs, so you often do not need to call these functions at all. Inside "{ ... }":

SpecMeaning
{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]
}