Skip to main content
Version: Zig 0.13.0

Advanced Formatting

So far we have only covered formatting specifiers. Format strings actually follow this format, where between each pair of square brackets is a parameter you have to replace with something.

{[position][specifier]:[fill][alignment][width].[precision]}

NameMeaning
PositionThe index of the argument that should be inserted
SpecifierA type-dependent formatting option
FillA single character used for padding
AlignmentOne of three characters < ^ or >; these are for left, middle and right alignment
WidthThe total width of the field (characters)
PrecisionHow many decimals a formatted number should have

Position usage.

const std = @import("std");
const expectEqualStrings = std.testing.expectEqualStrings;
const bufPrint = std.fmt.bufPrint;
test "position" {
var b: [3]u8 = undefined;

try expectEqualStrings(
"aab",
try bufPrint(&b, "{0s}{0s}{1s}", .{ "a", "b" }),
);
}

Fill, alignment and width being used.

const std = @import("std");
const expectEqualStrings = std.testing.expectEqualStrings;
const bufPrint = std.fmt.bufPrint;
test "fill, alignment, width" {
var b: [6]u8 = undefined;

try expectEqualStrings(
"hi! ",
try bufPrint(&b, "{s: <5}", .{"hi!"}),
);

try expectEqualStrings(
"_hi!__",
try bufPrint(&b, "{s:_^6}", .{"hi!"}),
);

try expectEqualStrings(
"!hi!",
try bufPrint(&b, "{s:!>4}", .{"hi!"}),
);
}

Using a specifier with precision.

const std = @import("std");
const expectEqualStrings = std.testing.expectEqualStrings;
const bufPrint = std.fmt.bufPrint;
test "precision" {
var b: [4]u8 = undefined;
try expectEqualStrings(
"3.14",
try bufPrint(&b, "{d:.2}", .{3.14159}),
);
}