🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Formatting

Formatting controls how a value looks when it is printed. Width, padding, and precision change the text without changing the value.

Width pads a value to a fixed size

The bars mark the edges of each field. A right-aligned value sits against the right edge, and a left-aligned value sits against the left edge.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("|{s:>6}|\n", .{"zig"});
    try out.print("|{s:<6}|\n", .{"zig"});
    try out.print("|{d:>5}|\n", .{42});
}

Zero padding and precision shape numbers

A zero before the alignment fills the field with zeros instead of spaces. A precision after a dot fixes the decimal places of a float.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{d:0>4}\n", .{42});
    try out.print("{d:0>3}\n", .{7});
    try out.print("{d:.2}\n", .{3.14159});
    try out.print("{d:.2}\n", .{12.5});
}

One value can print in decimal, hex, or binary

The specifier picks the base for an integer. A width can still pad the result, as the last line shows.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{x}\n", .{255});
    try out.print("{d}\n", .{255});
    try out.print("{b}\n", .{10});
    try out.print("{x:0>4}\n", .{255});
}

Example

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{d:0>4}\n", .{7});
    try out.print("{s:<8}{d:.2}\n", .{ "apples", 2.5 });
    try out.print("{s:<8}{d:.2}\n", .{ "pears", 12.75 });
    try out.print("{x}\n", .{255});
}

Key points

  • Field width: the number in a spec sets how wide the printed field is.
  • Alignment: > right-aligns a value in its field and < left-aligns it.
  • Zero pad: 0>4 fills the empty space with zeros, turning 42 into 0042.
  • Precision: a dot and a count fix how many decimal places a float shows.
  • Hex: {x} prints an integer in lowercase hexadecimal.
  • Binary: {b} prints an integer in binary.

In this example, the first line zero-pads the id 7 to four places, giving 0007. Each row left-aligns the name in a field of width 8, so the prices line up. Each price prints with two decimal places, and the last line shows 255 in hex as ff.

Note

formatting changes only the printed text, never the stored value.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which print spec turns the number 42 into 0042?