From 091aa54a3ed74b8a19f44ffb20e29c5f81de0c58 Mon Sep 17 00:00:00 2001 From: Marc Tiehuis Date: Sun, 24 Mar 2024 12:53:08 +1300 Subject: [PATCH] fix comptime float formatting Closes #19379 Closes #18046 --- lib/std/fmt.zig | 2 ++ lib/std/fmt/format_float.zig | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index 511314fb12cf084ce95b29325a29b8db8f2e84e1..df8397fb93303f47fbed9a040b02a3d67970e0d7 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -1839,6 +1839,8 @@ test comptimePrint { try std.testing.expectEqualSlices(u8, "100", comptimePrint("{}", .{100})); try std.testing.expectEqualStrings("30", comptimePrint("{d}", .{30.0})); try std.testing.expectEqualStrings("30.0", comptimePrint("{d:3.1}", .{30.0})); + try std.testing.expectEqualStrings("0.05", comptimePrint("{d}", .{0.05})); + try std.testing.expectEqualStrings("5e-2", comptimePrint("{e}", .{0.05})); } test "parse u64 digit too big" { diff --git a/lib/std/fmt/format_float.zig b/lib/std/fmt/format_float.zig index b2194099bba4a547e5403e5d0819ab8c68c44db2..13a3f3aad411a62d98973c746e694f9fc8ad8b75 100644 --- a/lib/std/fmt/format_float.zig +++ b/lib/std/fmt/format_float.zig @@ -270,9 +270,9 @@ pub fn formatDecimal(buf: []u8, f_: FloatDecimal128, precision: ?usize) FormatEr // fixed bound: leading_digit(1) + point(1) const req_bytes = if (f.exponent >= 0) - 2 + @abs(f.exponent) + olength + (precision orelse 0) + @as(usize, 2) + @abs(f.exponent) + olength + (precision orelse 0) else - 2 + @max(@abs(f.exponent) + olength, precision orelse 0); + @as(usize, 2) + @max(@abs(f.exponent) + olength, precision orelse 0); if (buf.len < req_bytes) { return error.BufferTooSmall; } -- 2.54.0