Overview
The std.fmt module provides string formatting and parsing capabilities, including conversion between strings and various numeric types, formatting options, and text manipulation.
Core Types
Alignment
pub const Alignment = enum {
left,
center,
right,
};
Defines text alignment options for formatted output.
Case
pub const Case = enum { lower, upper };
Specifies character case for formatting operations.
Options
pub const Options = struct {
precision: ?usize = null,
width: ?usize = null,
alignment: Alignment = .right,
fill: u8 = ' ',
};
Number of decimal places for floating point numbers, or null for automatic.
Minimum width of the formatted output.
Text alignment within the specified width. Defaults to .right.
Fill character for padding. Defaults to space (’ ’).
Number
pub const Number = struct {
mode: Mode = .decimal,
case: Case = .lower,
precision: ?usize = null,
width: ?usize = null,
alignment: Alignment = .right,
fill: u8 = ' ',
pub const Mode = enum {
decimal,
binary,
octal,
hex,
scientific,
};
};
Formatting options specific to numeric types.
bufPrint
pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintError![]u8
Prints a format string into a buffer and returns a slice of the bytes printed.
Destination buffer for the formatted output.
Format string with placeholders like {}.
Tuple of values to format.
Slice of the buffer containing the formatted output.
Example:
const std = @import("std");
var buf: [100]u8 = undefined;
const result = try std.fmt.bufPrint(&buf, "Hello, {}!", .{"World"});
// result is "Hello, World!"
allocPrint
pub fn allocPrint(gpa: Allocator, comptime fmt: []const u8, args: anytype) Allocator.Error![]u8
Allocates and returns a formatted string. Caller owns the returned memory.
Allocator to use for the output buffer.
Example:
const allocator = std.heap.page_allocator;
const str = try std.fmt.allocPrint(allocator, "x = {}", .{42});
defer allocator.free(str);
comptimePrint
pub inline fn comptimePrint(comptime fmt: []const u8, args: anytype) *const [count(fmt, args):0]u8
Formats a string at compile time. Returns a pointer to a null-terminated string literal.
Example:
const msg = std.fmt.comptimePrint("Version: {}.{}.{}", .{1, 0, 0});
// msg is a compile-time string: "Version: 1.0.0"
Parsing Functions
parseInt
pub fn parseInt(comptime T: type, buf: []const u8, base: u8) ParseIntError!T
Parses a string as a signed or unsigned integer.
The integer type to parse into (e.g., i32, u64).
Number base (2-36). Use 0 for automatic detection (0b, 0o, 0x prefixes).
Example:
const value = try std.fmt.parseInt(i32, "-42", 10);
// value is -42
const hex_value = try std.fmt.parseInt(u32, "0xFF", 0);
// hex_value is 255
const binary = try std.fmt.parseInt(u8, "0b1010", 0);
// binary is 10
parseUnsigned
pub fn parseUnsigned(comptime T: type, buf: []const u8, base: u8) ParseIntError!T
Parses a string as an unsigned integer. Similar to parseInt but does not accept sign prefixes.
Example:
const value = try std.fmt.parseUnsigned(u16, "65535", 10);
// value is 65535
parseFloat
pub fn parseFloat(comptime T: type, buf: []const u8) ParseFloatError!T
Parses a string as a floating point number.
The float type to parse into (e.g., f32, f64).
String representation of the number.
Example:
const pi = try std.fmt.parseFloat(f64, "3.14159");
const sci = try std.fmt.parseFloat(f32, "1.23e-4");
parseIntSizeSuffix
pub fn parseIntSizeSuffix(buf: []const u8, digit_base: u8) ParseIntError!usize
Parses numbers with size suffixes like ‘2G’, ‘2Gi’, or ‘2GiB’.
Example:
const size = try std.fmt.parseIntSizeSuffix("2KiB", 10);
// size is 2048
const decimal_size = try std.fmt.parseIntSizeSuffix("2kB", 10);
// decimal_size is 2000
Utility Functions
bytesToHex
pub fn bytesToHex(input: anytype, case: Case) [input.len * 2]u8
Encodes bytes as hexadecimal characters.
Example:
const bytes = "hello";
const hex = std.fmt.bytesToHex(bytes, .lower);
// hex is "68656c6c6f"
hexToBytes
pub fn hexToBytes(out: []u8, input: []const u8) ![]u8
Decodes a hexadecimal string into bytes.
Example:
var out: [5]u8 = undefined;
const result = try std.fmt.hexToBytes(&out, "68656c6c6f");
// result is "hello"
digits2
pub fn digits2(value: u8) [2]u8
Converts values in range [0, 100) to a base 10 string efficiently.
Example:
const digits = std.fmt.digits2(42);
// digits is "42"
Format strings use {} as placeholders with optional formatting directives:
{d} - Decimal integer
{x} - Lowercase hexadecimal
{X} - Uppercase hexadecimal
{b} - Binary
{o} - Octal
{c} - Character
{s} - String
{e} - Scientific notation
{any} - Debug format
{*} - Pointer
Width and Alignment:
"{:5}" // Width of 5, right-aligned
"{:<5}" // Left-aligned
"{:^5}" // Center-aligned
"{:=>5}" // Right-aligned, filled with '='
"{:4.2}" // Width 4, precision 2
Example:
var buf: [100]u8 = undefined;
const result = try std.fmt.bufPrint(&buf,
"Int: {d}, Hex: 0x{X:0>4}, Float: {d:.2}",
.{42, 255, 3.14159}
);
// result is "Int: 42, Hex: 0x00FF, Float: 3.14"
Error Types
ParseIntError
pub const ParseIntError = error{
Overflow,
InvalidCharacter,
};
BufPrintError
pub const BufPrintError = error{
NoSpaceLeft,
};