From c85efef3126eabde097761ae080ca007ba46d926 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Mon, 30 Dec 2019 10:28:27 -1000 Subject: [PATCH] More showpoint fixes and tests (#1498) --- include/fmt/format-inl.h | 5 +++-- include/fmt/format.h | 3 ++- test/format-test.cc | 3 +++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/include/fmt/format-inl.h b/include/fmt/format-inl.h index 983ce9ec..b78966b0 100644 --- a/include/fmt/format-inl.h +++ b/include/fmt/format-inl.h @@ -1112,7 +1112,7 @@ int snprintf_float(T value, int precision, float_specs specs, char format[max_format_size]; char* format_ptr = format; *format_ptr++ = '%'; - if (specs.showpoint) *format_ptr++ = '#'; + if (specs.showpoint && specs.format == float_format::hex) *format_ptr++ = '#'; if (precision >= 0) { *format_ptr++ = '.'; *format_ptr++ = '*'; @@ -1351,7 +1351,8 @@ FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) { internal::utf8_to_utf16 u16(string_view(buffer.data(), buffer.size())); auto written = DWORD(); if (!WriteConsoleW(reinterpret_cast(_get_osfhandle(fd)), - u16.c_str(), static_cast(u16.size()), &written, nullptr)) { + u16.c_str(), static_cast(u16.size()), &written, + nullptr)) { throw format_error("failed to write to console"); } return; diff --git a/include/fmt/format.h b/include/fmt/format.h index 3e29abac..eef086ee 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -1125,9 +1125,10 @@ template class float_writer { if (specs_.precision >= 0 && specs_.precision < num_zeros) num_zeros = specs_.precision; int num_digits = num_digits_; + // Remove trailing zeros. if (!specs_.showpoint) while (num_digits > 0 && digits_[num_digits - 1] == '0') --num_digits; - if (num_zeros != 0 || num_digits != 0) { + if (num_zeros != 0 || num_digits != 0 || specs_.showpoint) { *it++ = decimal_point_; it = std::fill_n(it, num_zeros, static_cast('0')); it = copy_str(digits_, digits_ + num_digits, it); diff --git a/test/format-test.cc b/test/format-test.cc index 1ba74d27..e68c1c60 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -926,6 +926,9 @@ TEST(FormatterTest, HashFlag) { EXPECT_EQ("-42.0", format("{0:#}", -42.0)); EXPECT_EQ("-42.0", format("{0:#}", -42.0l)); EXPECT_EQ("4.e+01", format("{:#.0e}", 42.0)); + EXPECT_EQ("0.", format("{:#.0f}", 0.01)); + auto s = format("{:#.0f}", 0.5); // MSVC's printf uses wrong rounding mode. + EXPECT_TRUE(s == "0." || s == "1."); EXPECT_THROW_MSG(format("{0:#", 'c'), format_error, "missing '}' in format string"); EXPECT_THROW_MSG(format("{0:#}", 'c'), format_error,