Format Specifiers
Inside {} interpolation you can add :spec to control value formatting.
The supported specifiers are:
| Spec | Effect | Example |
|---|---|---|
:.Nf |
N decimal places | {pi:.2f} → 3.14 |
:0Nd |
integer with N digits zero-padded | {n:04d} → 0042 |
:#x |
integer in hexadecimal with 0x prefix |
{255:#x} → 0xff |
Float precision, zero-padding, and hex in interpolation.
04-format-specs.zolo
// Feature: Format specs in interpolation
// Syntax: `"{expr:spec}"` — spec after `:`
// When to use: float precision, zero-padding, numeric bases.
// -- Float precision (`.Nf`) ------------------------------------
let pi = 3.14159265
print("{pi:.2f}") // 3.14
print("{pi:.4f}") // 3.1416
print("{pi:.0f}") // 3
// -- Numeric zero-padding (`0Nd`) -------------------------------
let n = 42
print("{n:04d}") // 0042
print("{n:08d}") // 00000042
// -- Hex with prefix (`#x`) ------------------------------------
print("{255:#x}") // 0xff
print("{16:#x}") // 0x10
// -- Practical combinations ------------------------------------
let price = 9.5
print("$ {price:.2f}") // $ 9.50
let id = 7
print("ID: {id:04d}") // ID: 0007
// Coordinates with 3 decimal places.
let x = 1.234567
let y = -0.5
print("({x:.3f}, {y:.3f})")
// expected: (1.235, -0.500)
// Sequential numeric IDs with zero-pad.
var i = 1
while i <= 3 {
print("user_{i:03d}")
i = i + 1
}
// expected:
// user_001
// user_002
// user_003
// NOTE: alignment (`>` and `<`) and binary/octal bases are not yet
// supported in the current interpolator. Use precision and zero-pad
// for the most common cases.
Note: alignment (
>,<) and octal/binary bases are not available in the current interpolator. Use precision and zero-padding for the most common cases.
See also