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

[3.9] bpo-40780: Fix failure of _Py_dg_dtoa to remove trailing zeros (GH-20435) #20514

Merged
merged 1 commit into from
May 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
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.0, "1.5e+03")
self.assertEqual("%#.3g" % 1505.0, "1.50e+03")

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

self.assertEqual(format(12300050.0, ".6g"), "1.23e+07")
self.assertEqual(format(12300050.0, "#.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.
11 changes: 11 additions & 0 deletions Python/dtoa.c
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@
* 7. _Py_dg_strtod has been modified so that it doesn't accept strings with
* leading whitespace.
*
* 8. A corner case where _Py_dg_dtoa didn't strip trailing zeros has been
* fixed. (bugs.python.org/issue40780)
*
***************************************************************/

/* Please send bug reports for the original dtoa.c code to David M. Gay (dmg
Expand Down Expand Up @@ -2563,6 +2566,14 @@ _Py_dg_dtoa(double dd, int mode, int ndigits,
}
++*s++;
}
else {
/* Strip trailing zeros. This branch was missing from the
original dtoa.c, leading to surplus trailing zeros in
some cases. See bugs.python.org/issue40780. */
while (s > s0 && s[-1] == '0') {
--s;
}
}
break;
}
}
Expand Down