string-formattingzig

How to format numbers with precision in strings when precision is only a runtime known value?


I have the following Zig snippet:

var buffer: [20]u8 = undefined;
const precise_string = std.fmt.bufPrint(&buffer, "{d:.d}", .{ max, precision }) catch unreachable;
std.debug.print("{}", .{precise_string.len});

I get this error:

 zig test src/root.zig 
/snap/zig/12539/lib/std/fmt.zig:294:13: error: extraneous trailing character '{'
            @compileError("extraneous trailing character '" ++ unicode.utf8EncodeComptime(ch) ++ "'");
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/snap/zig/12539/lib/std/fmt.zig:155:55: note: called from here
        const placeholder = comptime Placeholder.parse(fmt[fmt_begin..fmt_end].*);
                                     ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~

I know the source of the error is the format specifier string, but I am not able to figure out how to fix it, what the actual problem is. I expected it would place the value of max at the start of the string and then after :. it would place the precision value.


Solution

  • the following format specifier with positional arguments worked out in the end try std.fmt.bufPrint(&buffer, "{[0]d:.[1]}", .{ max, precision })