typestar

std.fmt in Zig

Format into a stack buffer and parse back out — no allocator in sight.

const std = @import("std");

pub fn main() !void {
    // bufPrint formats into a stack buffer -- no allocator involved.
    var buf: [48]u8 = undefined;
    const line = try std.fmt.bufPrint(&buf, "day {d} mean {d:.2}", .{
        3, 68.14,
    });
    std.debug.print("built: [{s}]\n", .{line});

    // parseInt and parseFloat go the other way.
    const day = try std.fmt.parseInt(u8, line[4..5], 10);
    const mean = try std.fmt.parseFloat(f32, "68.14");
    std.debug.print("parsed back: day {d}, mean {d:.2}\n", .{ day, mean });
}

How it works

  1. bufPrint writes into buf and returns the slice it used.
  2. {d:.2} fixes the decimals the same way in every print.
  3. parseInt and parseFloat return error unions, unwrapped here with try.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
494
Tokens
133
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 123 seconds.

Type this snippet

Step 2 of 3 in The standard library, step 23 of 27 in Language basics.

← Previous Next →