std.fmt
import std.fmt
fmt.format(r"{} of {}", 3, 10) # "3 of 10"
fmt.fixed(3.14159, 2) # "3.14"
fmt.inspect([1, { a: 1 }]) # "list[2] [int 1, map{1} {a: int 1}]"
Removed in 0.61
pad_left, pad_right, repeat and truncate duplicated std.str; they were deprecated in 0.59 and removed in 0.61. Calling one is an error naming its replacement, and the replacements give the same answers:
| removed | use |
|---|---|
fmt.pad_left("7", 4, "0") | str.pad_start("7", 4, "0") |
fmt.pad_right("ab", 5) | str.pad_end("ab", 5) |
fmt.repeat("-", 20) | str.repeat("-", 20) |
fmt.truncate(long, 40) | long[..40] (a slice clamps, so a short string is unchanged) |
inspect
fmt.inspect(v) renders any value with its types and structure - "list[2] [int 1, map{1} {a: int 1}]" - with map and struct keys sorted, so the output is deterministic, and a secret shown as [secret], so inspecting a config map cannot leak a credential. It was debug.inspect until 0.59.
format needs a raw string
fmt.format(r"{} of {}", 3, 10) # correct
fmt.format("{} of {}", 3, 10) # error: Expected expression in string interpolation
A normal string triggers Ecko's own {expr} interpolation at parse time, so {} would be read as an empty expression. The r"..." prefix suppresses interpolation and hands the placeholders to format.
This trips everyone once. If you get a parse error pointing at a format call, that is why.
When to use which
Most of the time you do not need format at all - interpolation is built into the language and reads better:
"{count} of {total}" # idiomatic
fmt.format(r"{} of {}", count, total)
Reach for format when the template is data: read from a config file, chosen from a table, or reused across call sites with different arguments.
Fixed decimal places
fmt.fixed(value, places) renders a number to a set number of decimals, padding with zeroes rather than trimming the text:
fmt.fixed(1.5, 3) # "1.500"
fmt.fixed(2.5, 0) # "3"
fmt.fixed(decimal("0.07"), 2) # "0.07"
Two details worth knowing. Halves go away from zero, so 2.5 at zero places is "3" - not the half-to-even most languages' formatters use. And a decimal is rounded in decimal, never through a float, so an exact 0.07 stays 0.07 instead of picking up a binary artefact. That makes it the one to reach for when formatting money.
Padding and truncating
Use std.str: pad_start, pad_end, center and zfill are character-aware, and a slice s[..n] truncates. For terminal tables where display width differs from character count, the tui package handles width properly.