Formatted Output

std.debug.print can also do formatted output. It takes a format string with {…} placeholders and the values to be substituted:

const std = @import("std");
const print = std.debug.print;

pub fn main() void {
    // Use {s} for strings, {d} for decimal numbers.
    print("{s} is about {d}\n", .{ "pi", 3.14 });
    print("\n", .{});

    // {x}, {o}, {b} are used to print numbers as
    // hexadecimal, octal, or binary.
    print("16 in hex/oct/binary:\n", .{});
    print("{x}, {o}, {b}\n", .{ 16, 16, 16 });
    print("\n", .{});

    // For most built-in types we can just use {}.
    print("{} {} {}\n", .{ true, 5, 3.14 });
    print("\n", .{});

    // Add a field width for vertically aligned output.
    print("1 KiB is {d:10} Byte\n", .{1 << 10});
    print("1 MiB is {d:10} Byte\n", .{1 << 20});
    print("1 GiB is {d:10} Byte\n", .{1 << 30});
    print("\n", .{});

    // {d:6.2} is field width 6 and 2 decimal digits.
    print("{d:3}°F is {d:6.2}°C\n", .{ 0, -17.7778 });
    print("{d:3}°F is {d:6.2}°C\n", .{ 50, 10.0 });
    print("{d:3}°F is {d:6.2}°C\n", .{ 100, 37.7778 });
}
$ zig run formatted.zig
pi is about 3.14

16 in hex/oct/binary:
10, 20, 10000

true 5 3.14

1 KiB is       1024 Byte
1 MiB is    1048576 Byte
1 GiB is 1073741824 Byte

  0°F is -17.78°C
 50°F is  10.00°C
100°F is  37.78°C

See std.Io.Writer.print for all all options.

Next example: Unit Tests.