From bc535fe73a8af0cc89480ece28f24a93d59e2a89 Mon Sep 17 00:00:00 2001 From: Vladislav Shchapov Date: Thu, 21 Mar 2024 01:31:32 +0500 Subject: [PATCH] Improve std::complex formatter to be compatible with P2197R0 (#3900) Signed-off-by: Vladislav Shchapov --- include/fmt/std.h | 13 +++++++++---- test/std-test.cc | 1 + 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/include/fmt/std.h b/include/fmt/std.h index 2d6012e3dc1f..7085cae8170a 100644 --- a/include/fmt/std.h +++ b/include/fmt/std.h @@ -595,10 +595,15 @@ struct formatter, Char> : nested_formatter { template FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt { - auto format = detail::string_literal{}; - return fmt::format_to(out, basic_string_view(format), - f->nested(c.real()), f->nested(c.imag())); + if (c.real() != 0) { + auto format_full = detail::string_literal{}; + return fmt::format_to(out, basic_string_view(format_full), + f->nested(c.real()), f->nested(c.imag())); + } + auto format_imag = detail::string_literal{}; + return fmt::format_to(out, basic_string_view(format_imag), + f->nested(c.imag())); } }; diff --git a/test/std-test.cc b/test/std-test.cc index 3fbcedf5764d..691b10976bd0 100644 --- a/test/std-test.cc +++ b/test/std-test.cc @@ -67,6 +67,7 @@ TEST(std_test, thread_id) { TEST(std_test, complex) { EXPECT_EQ(fmt::format("{}", std::complex(1, 2.2)), "(1+2.2i)"); + EXPECT_EQ(fmt::format("{}", std::complex(0, 2.2)), "2.2i"); EXPECT_EQ(fmt::format("{:>20.2f}", std::complex(1, 2.2)), " (1.00+2.20i)"); }