Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix %S formatting for chrono durations with leading zeroes #3814

Merged
merged 7 commits into from
Feb 7, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add tests and single digit case
js324 committed Jan 17, 2024
commit e81ef54b30528a4416014bbf840dc2b70ce6cf09
38 changes: 26 additions & 12 deletions include/fmt/chrono.h
Original file line number Diff line number Diff line change
@@ -1161,23 +1161,37 @@ void write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) {
const int old_num_digits = detail::count_digits(n);
auto roundingDigit = n % 10;
n /= 10;
if (roundingDigit > 5 || (roundingDigit == 5 && n % 10 % 2 != 0)) {
n += 1;
}
if (old_num_digits == detail::count_digits(n)) {
if (leading_zeroes) {
out = std::fill_n(out, leading_zeroes-1, '0');
*out++ = '1';
out = std::fill_n(out, remaining, '0');
if (n) {
if (roundingDigit > 5 || (roundingDigit == 5 && n % 10 % 2 != 0)) {
n += 1;
}
if (old_num_digits == detail::count_digits(n)) {
if (leading_zeroes) {
out = std::fill_n(out, leading_zeroes-1, '0');
*out++ = '1';
out = std::fill_n(out, remaining, '0');
}
else {
n -= 1;
out = format_decimal<Char>(out, n, remaining).end;
}
}
else {
n -= 1;
out = std::fill_n(out, leading_zeroes, '0');
out = format_decimal<Char>(out, n, remaining).end;
}
}
else {
out = std::fill_n(out, leading_zeroes, '0');
out = format_decimal<Char>(out, n, remaining).end;
else {
if (roundingDigit >= 5) {
if (leading_zeroes) {
out = std::fill_n(out, leading_zeroes-1, '0');
*out++ = '1';
out = std::fill_n(out, remaining, '0');
}
}
else {
out = std::fill_n(out, leading_zeroes, '0');
}
}
return;
}
4 changes: 4 additions & 0 deletions test/chrono-test.cc
Original file line number Diff line number Diff line change
@@ -803,6 +803,10 @@ TEST(chrono_test, cpp20_duration_subsecond_support) {
"12.1");
EXPECT_EQ(fmt::format("{:.2%S}", std::chrono::milliseconds{99999}),
"39.99");
EXPECT_EQ(fmt::format("{:.2%S}", std::chrono::milliseconds{1000}),
"01.00");
EXPECT_EQ(fmt::format("{:.3%S}", std::chrono::milliseconds{1}),
"00.001");
EXPECT_EQ(fmt::format("{:.3%S}", std::chrono::seconds{1234}), "34.000");
EXPECT_EQ(fmt::format("{:.3%S}", std::chrono::hours{1234}), "00.000");
EXPECT_EQ(fmt::format("{:.5%S}", dms(1.234)), "00.00123");