From 532e846b86824c5af27a2eb160f50b53b76aa9a4 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Fri, 15 Jan 2021 11:07:55 -0800 Subject: [PATCH] Fix width computation in float formatter --- include/fmt/format.h | 5 +++-- test/format-test.cc | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index dab19368..9cb73c38 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -1962,11 +1962,12 @@ OutputIt write_float(OutputIt out, const DecimalFP& fp, fspecs.precision < num_zeros) { num_zeros = fspecs.precision; } - size += 2 + to_unsigned(num_zeros); + bool pointy = num_zeros != 0 || significand_size != 0 || fspecs.showpoint; + size += 1 + (pointy ? 1 : 0) + to_unsigned(num_zeros); return write_padded(out, specs, size, [&](iterator it) { if (sign) *it++ = static_cast(data::signs[sign]); *it++ = zero; - if (num_zeros == 0 && significand_size == 0 && !fspecs.showpoint) return it; + if (!pointy) return it; *it++ = decimal_point; it = detail::fill_n(it, num_zeros, zero); return write_significand(it, significand, significand_size); diff --git a/test/format-test.cc b/test/format-test.cc index 860cdf69..74743e7a 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -871,6 +871,7 @@ TEST(FormatterTest, Width) { EXPECT_EQ(format("{:*^5}", "🤡"), "**🤡**"); EXPECT_EQ(format("{:#6}", 42.0), " 42.0"); EXPECT_EQ(format("{:6c}", static_cast('x')), "x "); + EXPECT_EQ(format("{:>06.0f}", 0.00884311), "000000"); } template inline T const_check(T value) { return value; }