Fix zero padding for localized integers (#4994)

This commit is contained in:
Nathan Chandrasekar 2026-10-31 13:15:44 -04:00 committed by GitHub
parent dc4675a400
commit 09a606d17a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 0 deletions

View File

@ -2248,10 +2248,17 @@ auto write_int(OutputIt out, UInt value, unsigned prefix,
unsigned size = (prefix != 0 ? prefix >> 24 : 0) + to_unsigned(num_digits) +
to_unsigned(grouping.count_separators(num_digits));
unsigned padding = 0;
if (specs.align() == align::numeric) {
auto width = to_unsigned(specs.width);
if (width > size) padding = width - size;
size += padding;
}
return write_padded<Char, align::right>(
out, specs, size, size, [&](reserve_iterator<OutputIt> it) {
for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
*it++ = static_cast<Char>(p & 0xff);
it = detail::fill_n(it, padding, static_cast<Char>('0'));
return grouping.apply(it, string_view(buffer.data(), buffer.size()));
});
}

View File

@ -2686,6 +2686,22 @@ TEST(format_test, format_locale) {
EXPECT_EQ(fmt::format(loc, "{:10Lo}", 12345), " 30,071");
}
TEST(format_test, format_int_locale_zero_padding) {
auto loc = std::locale::classic();
EXPECT_EQ(fmt::format(loc, "{:08L}", -12), "-0000012");
EXPECT_EQ(fmt::format(loc, "{:+08L}", 12), "+0000012");
EXPECT_EQ(fmt::format(loc, "{: 08L}", 12), " 0000012");
EXPECT_EQ(fmt::format(loc, "{:08L}", 12), "00000012");
EXPECT_EQ(fmt::format(loc, "{:02L}", -12), "-12");
EXPECT_EQ(fmt::format(loc, "{:>08L}", -12), " -12");
EXPECT_EQ(fmt::format(loc, "{:0>8L}", -12), "00000-12");
loc = std::locale(loc, new fmt::format_facet<std::locale>(","));
EXPECT_EQ(fmt::format(loc, "{:08L}", -1234), "-001,234");
EXPECT_EQ(fmt::format(loc, "{:#010Lx}", -0x1234), "-0x001,234");
EXPECT_EQ(fmt::format(loc, "{:#010Lb}", -10), "-0b001,010");
EXPECT_EQ(fmt::format(loc, "{:#08Lo}", -01234), "-001,234");
}
#endif // FMT_USE_LOCALE
struct convertible_to_nonconst_cstring {