Use std.fmt to print negative number padding-zero

as title, expect result equal with c code.
Is there a native implementation?

c code

printf("%03d\n", -8);    // result:  -08
printf("%08.3f\n", -8.0); // result: -008.000

zig code

std.debug.print("{d:0>3}\n", .{-8});   // result:  0-8
std.debug.print("{d:0>8.3}\n", .{-8.0}); //result: 00-8.000

FYI this is a known bug:

3 Likes

As far as I remember, 0 after : is a filler.
Output is 8 char wide, 6 is occupied with -8.000, 2 places in the beginning are filled with 0.

See also this topic

Until that bug is fixed, you could do some hacky stuff like:

const std = @import("std");

fn sign(n: anytype, plus: bool) []const u8 {
    return if (n < 0)
        "-"
    else if (plus)
        "+"
    else
        "";
}

fn adjustLen(l: usize, n: anytype, plus: bool) usize {
    return if (n < 0)
        l - 1
    else if (plus)
        l - 1
    else
        l;
}

const Options = struct {
    width: usize = 8,
    precision: usize = 2,
    plus: bool = false,
};

inline fn abs(n: anytype) @TypeOf(n) {
    return if (n < 0) -n else n;
}

fn numPrint(n: anytype, options: Options) void {
    std.debug.print("{s}{d:0>[2].[3]}\n", .{
        sign(n, options.plus),
        abs(n),
        adjustLen(options.width, n, options.plus),
        options.precision,
    });
}

pub fn main() !void {
    const nf = -3.1415;
    numPrint(nf, .{});

    const pf = 3.1415;
    numPrint(pf, .{});
    numPrint(pf, .{ .plus = true });

    const ni = -31415;
    numPrint(ni, .{});

    const pi = 31415;
    numPrint(pi, .{});
    numPrint(pi, .{ .plus = true });
}

Output

-0003.14
00003.14
+0003.14
-0031415
00031415
+0031415
2 Likes