Skip to content

Commit

Permalink
Fix format of negative std::complex without sign option in format string
Browse files Browse the repository at this point in the history
Signed-off-by: Vladislav Shchapov <vladislav@shchapov.ru>
  • Loading branch information
phprus committed Jul 3, 2024
1 parent 991856a commit e205a70
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
11 changes: 8 additions & 3 deletions include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -631,8 +631,7 @@ struct formatter<std::atomic_flag, Char> : formatter<bool, Char> {
#endif // __cpp_lib_atomic_flag_test

FMT_EXPORT
template <typename T, typename Char>
struct formatter<std::complex<T>, Char> {
template <typename T, typename Char> struct formatter<std::complex<T>, Char> {
private:
int width_;
detail::fill_t fill_;
Expand Down Expand Up @@ -666,7 +665,13 @@ struct formatter<std::complex<T>, Char> {
if (c.real() != 0) {
auto format_full = detail::string_literal<Char, '(', '{', '}', '+', '{',
'}', 'i', ')'>{};
return fmt::format_to(out, basic_string_view<Char>(format_full),
auto format_full_neg =
detail::string_literal<Char, '(', '{', '}', '{', '}', 'i', ')'>{};

if (c.imag() >= 0)
return fmt::format_to(out, basic_string_view<Char>(format_full),
f->nested(c.real()), f->nested(c.imag()));
return fmt::format_to(out, basic_string_view<Char>(format_full_neg),
f->nested(c.real()), f->nested(c.imag()));
}
auto format_imag = detail::string_literal<Char, '{', '}', 'i'>{};
Expand Down
6 changes: 6 additions & 0 deletions test/std-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,15 @@ 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>(1, -2.2)), "(1-2.2i)");
EXPECT_EQ(fmt::format("{}", std::complex<double>(0, 2.2)), "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)");
EXPECT_EQ(fmt::format("{:<20.2f}", std::complex<double>(1, 2.2)),
"(1.00+2.20i) ");
EXPECT_EQ(fmt::format("{:<20.2f}", std::complex<double>(1, -2.2)),
"(1.00-2.20i) ");
}

#ifdef __cpp_lib_source_location
Expand Down

0 comments on commit e205a70

Please sign in to comment.