From 7e6827521aeec2b9f7a43258e6d08406834e667f Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Thu, 17 Sep 2020 08:11:00 -0700 Subject: [PATCH] Remove trailing zeros when using fallback formatter (#1873) --- include/fmt/format-inl.h | 44 +++++++++++++++++++++------------------- test/format-test.cc | 1 + 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/include/fmt/format-inl.h b/include/fmt/format-inl.h index 42495300..2a6efc78 100644 --- a/include/fmt/format-inl.h +++ b/include/fmt/format-inl.h @@ -1162,28 +1162,30 @@ int format_float(T value, int precision, float_specs specs, buffer& buf) { return exp; } buf.try_resize(to_unsigned(handler.size)); - } else { - fp normalized = normalize(fp(value)); - const auto cached_pow = get_cached_power( - min_exp - (normalized.e + fp::significand_size), cached_exp10); - normalized = normalized * cached_pow; - fixed_handler handler{buf.data(), 0, precision, -cached_exp10, fixed}; - if (grisu_gen_digits(normalized, 1, exp, handler) == digits::error) { - exp += handler.size - cached_exp10 - 1; - fallback_format(value, handler.precision, specs.binary32, buf, exp); - return exp; - } - int num_digits = handler.size; - if (!fixed && !specs.showpoint) { - // Remove trailing zeros. - while (num_digits > 0 && buf[num_digits - 1] == '0') { - --num_digits; - ++exp; - } - } - buf.try_resize(to_unsigned(num_digits)); + return exp - cached_exp10; } - return exp - cached_exp10; + fp normalized = normalize(fp(value)); + const auto cached_pow = get_cached_power( + min_exp - (normalized.e + fp::significand_size), cached_exp10); + normalized = normalized * cached_pow; + fixed_handler handler{buf.data(), 0, precision, -cached_exp10, fixed}; + if (grisu_gen_digits(normalized, 1, exp, handler) == digits::error) { + exp += handler.size - cached_exp10 - 1; + fallback_format(value, handler.precision, specs.binary32, buf, exp); + } else { + exp -= cached_exp10; + buf.try_resize(to_unsigned(handler.size)); + } + if (!fixed && !specs.showpoint) { + // Remove trailing zeros. + auto num_digits = buf.size(); + while (num_digits > 0 && buf[num_digits - 1] == '0') { + --num_digits; + ++exp; + } + buf.try_resize(num_digits); + } + return exp; } template diff --git a/test/format-test.cc b/test/format-test.cc index 2d017a81..7870e9d0 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -1248,6 +1248,7 @@ TEST(FormatterTest, FormatDouble) { EXPECT_EQ("392.65", format("{:}", 392.65)); EXPECT_EQ("392.65", format("{:g}", 392.65)); EXPECT_EQ("392.65", format("{:G}", 392.65)); + EXPECT_EQ("4.9014e+06", format("{:g}", 4.9014e6)); EXPECT_EQ("392.650000", format("{:f}", 392.65)); EXPECT_EQ("392.650000", format("{:F}", 392.65)); EXPECT_EQ("42", format("{:L}", 42.0));