Skip to content

bpo-40780: Fix failure of _Py_dg_dtoa to remove trailing zeros #20435

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

Merged
merged 5 commits into from
May 29, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
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
11 changes: 11 additions & 0 deletions Lib/test/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,17 @@ def test_precision_c_limits(self):
with self.assertRaises(ValueError) as cm:
format(c, ".%sf" % (INT_MAX + 1))

def test_g_format_has_no_trailing_zeros(self):
# regression test for bugs.python.org/issue40780
self.assertEqual("%.3g" % 1505, "1.5e+03")
self.assertEqual("%#.3g" % 1505, "1.50e+03")

self.assertEqual(format(1505, ".3g"), "1.5e+03")
self.assertEqual(format(1505, "#.3g"), "1.50e+03")

self.assertEqual(format(12300050, ".6g"), "1.23e+07")
self.assertEqual(format(12300050, "#.6g"), "1.23000e+07")


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a corner case where g-style string formatting of a float failed to
remove trailing zeros.
12 changes: 12 additions & 0 deletions Python/dtoa.c
Original file line number Diff line number Diff line change
Expand Up @@ -2563,6 +2563,18 @@ _Py_dg_dtoa(double dd, int mode, int ndigits,
}
++*s++;
}
/* This branch was missing from the original dtoa.c, leading
to surplus trailing zeros in some cases.
See bugs.python.org/issue40780. */
else {
/* At the beginning of the for loop we have 10**k <= d; it
follows that on the first iteration, ds <= dval(&u), and
so the first digit written to s is nonzero and it's safe
to strip trailing zeros. */
assert(k_check == 0);
while(*--s == '0');
s++;
}
break;
}
}
Expand Down