Skip to content

Commit

Permalink
Improve std::complex formatter to be compatible with P2197R0
Browse files Browse the repository at this point in the history
Signed-off-by: Vladislav Shchapov <vladislav@shchapov.ru>
  • Loading branch information
phprus committed Mar 19, 2024
1 parent 365c3fb commit 6dd74e8
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
14 changes: 10 additions & 4 deletions include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -595,10 +595,16 @@ struct formatter<std::complex<F>, Char> : nested_formatter<F, Char> {

template <typename OutputIt>
FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt {
auto format = detail::string_literal<Char, '(', '{', '}', '+', '{', '}',
'i', ')'>{};
return fmt::format_to(out, basic_string_view<Char>(format),
f->nested(c.real()), f->nested(c.imag()));
if (c.real() != 0) {
auto format_full = detail::string_literal<Char, '(', '{', '}', '+', '{',
'}', 'i', ')'>{};
return fmt::format_to(out, basic_string_view<Char>(format_full),
f->nested(c.real()), f->nested(c.imag()));
} else {
auto format_imag = detail::string_literal<Char, '{', '}', 'i'>{};
return fmt::format_to(out, basic_string_view<Char>(format_imag),
f->nested(c.imag()));
}
}
};

Expand Down
1 change: 1 addition & 0 deletions test/std-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ TEST(std_test, thread_id) {

TEST(std_test, complex) {
EXPECT_EQ(fmt::format("{}", std::complex<double>(1, 2.2)), "(1+2.2i)");
EXPECT_EQ(fmt::format("{}", std::complex<double>(0, 2.2)), "2.2i");
EXPECT_EQ(fmt::format("{:>20.2f}", std::complex<double>(1, 2.2)),
" (1.00+2.20i)");
}
Expand Down

0 comments on commit 6dd74e8

Please sign in to comment.