8000 bpo-40780: Fix failure of _Py_dg_dtoa to remove trailing zeros (GH-20… · python/cpython@ad088ca · GitHub
[go: up one dir, main page]

Skip to content

Commit ad088ca

Browse files
bpo-40780: Fix failure of _Py_dg_dtoa to remove trailing zeros (GH-20435) (GH-20514)
* Fix failure of _Py_dg_dtoa to remove trailing zeros * Add regression test and news entry * Add explanation about why it's safe to strip trailing zeros * Make code safer, clean up comments, add change note at top of file * Nitpick: avoid implicit int-to-float conversion in tests (cherry picked from commit 895c9c1) Co-authored-by: Mark Dickinson <mdickinson@enthought.com>
1 parent 8fcc147 commit ad088ca

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

Lib/test/test_format.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,17 @@ def test_precision_c_limits(self):
484484
with self.assertRaises(ValueError) as cm:
485485
format(c, ".%sf" % (INT_MAX + 1))
486486

487+
def test_g_format_has_no_trailing_zeros(self):
488+
# regression test for bugs.python.org/issue40780
489+
self.assertEqual("%.3g" % 1505.0, "1.5e+03")
490+
self.assertEqual("%#.3g" % 1505.0, "1.50e+03")
491+
492+
self.assertEqual(format(1505.0, ".3g"), "1.5e+03")
493+
self.assertEqual(format(1505.0, "#.3g"), "1.50e+03")
494+
495+
self.assertEqual(format(12300050.0, ".6g"), "1.23e+07")
496+
self.assertEqual(format(12300050.0, "#.6g"), "1.23000e+07")
497+
487498

488499
if __name__ == "__main__":
489500
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a corner case where g-style string formatting of a float failed to
2+
remove trailing zeros.

Python/dtoa.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@
6464
* 7. _Py_dg_strtod has been modified so that it doesn't accept strings with
6565
* leading whitespace.
6666
*
67+
* 8. A corner case where _Py_dg_dtoa didn't strip trailing zeros has been
68+
* fixed. (bugs.python.org/issue40780)
69+
*
6770
***************************************************************/
6871

6972
/* Please send bug reports for the original dtoa.c code to David M. Gay (dmg
@@ -2563,6 +2566,14 @@ _Py_dg_dtoa(double dd, int mode, int ndigits,
25632566
}
25642567
++*s++;
25652568
}
2569+
else {
2570+
/* Strip trailing zeros. This branch was missing from the
2571+
original dtoa.c, leading to surplus trailing zeros in
2572+
some cases. See bugs.python.org/issue40780. */
2573+
while (s > s0 && s[-1] == '0') {
2574+
--s;
2575+
}
2576+
}
25662577
break;
25672578
}
25682579
}

0 commit comments

Comments
 (0)
0