Remove trailing zeros when using fallback formatter (#1873)

This commit is contained in:
Victor Zverovich
2020-09-17 08:11:00 -07:00
parent 1d696dc280
commit 7e6827521a
2 changed files with 24 additions and 21 deletions

View File

@ -1162,7 +1162,8 @@ int format_float(T value, int precision, float_specs specs, buffer<char>& buf) {
return exp; return exp;
} }
buf.try_resize(to_unsigned(handler.size)); buf.try_resize(to_unsigned(handler.size));
} else { return exp - cached_exp10;
}
fp normalized = normalize(fp(value)); fp normalized = normalize(fp(value));
const auto cached_pow = get_cached_power( const auto cached_pow = get_cached_power(
min_exp - (normalized.e + fp::significand_size), cached_exp10); min_exp - (normalized.e + fp::significand_size), cached_exp10);
@ -1171,19 +1172,20 @@ int format_float(T value, int precision, float_specs specs, buffer<char>& buf) {
if (grisu_gen_digits(normalized, 1, exp, handler) == digits::error) { if (grisu_gen_digits(normalized, 1, exp, handler) == digits::error) {
exp += handler.size - cached_exp10 - 1; exp += handler.size - cached_exp10 - 1;
fallback_format(value, handler.precision, specs.binary32, buf, exp); fallback_format(value, handler.precision, specs.binary32, buf, exp);
return exp; } else {
exp -= cached_exp10;
buf.try_resize(to_unsigned(handler.size));
} }
int num_digits = handler.size;
if (!fixed && !specs.showpoint) { if (!fixed && !specs.showpoint) {
// Remove trailing zeros. // Remove trailing zeros.
auto num_digits = buf.size();
while (num_digits > 0 && buf[num_digits - 1] == '0') { while (num_digits > 0 && buf[num_digits - 1] == '0') {
--num_digits; --num_digits;
++exp; ++exp;
} }
buf.try_resize(num_digits);
} }
buf.try_resize(to_unsigned(num_digits)); return exp;
}
return exp - cached_exp10;
} }
template <typename T> template <typename T>

View File

@ -1248,6 +1248,7 @@ TEST(FormatterTest, FormatDouble) {
EXPECT_EQ("392.65", format("{:}", 392.65)); EXPECT_EQ("392.65", format("{:}", 392.65));
EXPECT_EQ("392.65", format("{:g}", 392.65)); EXPECT_EQ("392.65", format("{:g}", 392.65));
EXPECT_EQ("392.65", format("{:G}", 392.65)); EXPECT_EQ("392.65", format("{:G}", 392.65));
EXPECT_EQ("4.9014e+06", format("{:g}", 4.9014e6));
EXPECT_EQ("392.650000", format("{:f}", 392.65)); EXPECT_EQ("392.650000", format("{:f}", 392.65));
EXPECT_EQ("392.650000", format("{:F}", 392.65)); EXPECT_EQ("392.650000", format("{:F}", 392.65));
EXPECT_EQ("42", format("{:L}", 42.0)); EXPECT_EQ("42", format("{:L}", 42.0));