Skip to content

Fixes floating point alignment in std.fmt.format #6002

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 11, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions lib/std/fmt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -560,13 +560,25 @@ fn formatFloatValue(
options: FormatOptions,
writer: anytype,
) !void {
// this buffer should be enough to display all decimal places of a decimal f64 number.
var buf: [512]u8 = undefined;
var buf_stream = std.io.fixedBufferStream(&buf);

if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "e")) {
return formatFloatScientific(value, options, writer);
formatFloatScientific(value, options, buf_stream.writer()) catch |err| switch (err) {
error.NoSpaceLeft => unreachable,
else => |e| return e,
};
} else if (comptime std.mem.eql(u8, fmt, "d")) {
return formatFloatDecimal(value, options, writer);
formatFloatDecimal(value, options, buf_stream.writer()) catch |err| switch (err) {
error.NoSpaceLeft => unreachable,
else => |e| return e,
};
} else {
@compileError("Unknown format string: '" ++ fmt ++ "'");
}

return formatBuf(buf_stream.getWritten(), options, writer);
}

pub fn formatText(
Expand Down Expand Up @@ -1791,3 +1803,17 @@ test "padding" {
try testFmt("==================Filled", "{:=>24}", .{"Filled"});
try testFmt(" Centered ", "{:^24}", .{"Centered"});
}

test "decimal float padding" {
var number: f32 = 3.1415;
try testFmt("left-pad: **3.141\n", "left-pad: {d:*>7.3}\n", .{number});
try testFmt("center-pad: *3.141*\n", "center-pad: {d:*^7.3}\n", .{number});
try testFmt("right-pad: 3.141**\n", "right-pad: {d:*<7.3}\n", .{number});
}

test "sci float padding" {
var number: f32 = 3.1415;
try testFmt("left-pad: **3.141e+00\n", "left-pad: {e:*>11.3}\n", .{number});
try testFmt("center-pad: *3.141e+00*\n", "center-pad: {e:*^11.3}\n", .{number});
try testFmt("right-pad: 3.141e+00**\n", "right-pad: {e:*<11.3}\n", .{number});
}