GeezerVison is showing github.com — bpo-40780: Fix failure of _Py_dg_dtoa to remove trailing zeros (GH-20… · python/cpython@ad088ca
File tree
Expand file treeCollapse file tree
Open diff view settings
Misc/NEWS.d/next/Core and Builtins
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: Lib/test/test_format.py +11Lines changed: 11 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -484,6 +484,17 @@ def test_precision_c_limits(self): |
484 | 484 | with self.assertRaises(ValueError) as cm: |
485 | 485 | format(c, ".%sf" % (INT_MAX + 1)) |
486 | 486 |
|
| 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 | + |
487 | 498 |
|
488 | 499 | if __name__ == "__main__": |
489 | 500 | unittest.main() |
Collapse file
Copy file name to clipboard +2Lines changed: 2 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +Fix a corner case where g-style string formatting of a float failed to |
| 2 | +remove trailing zeros. |
Collapse file
Copy file name to clipboardExpand all lines: Python/dtoa.c +11Lines changed: 11 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
64 | 64 | * 7. _Py_dg_strtod has been modified so that it doesn't accept strings with |
65 | 65 | * leading whitespace. |
66 | 66 | * |
| 67 | + * 8. A corner case where _Py_dg_dtoa didn't strip trailing zeros has been |
| 68 | + * fixed. (bugs.python.org/issue40780) |
| 69 | + * |
67 | 70 | ***************************************************************/ |
68 | 71 |
|
69 | 72 | /* 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, |
2563 | 2566 | } |
2564 | 2567 | ++*s++; |
2565 | 2568 | } |
| 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 | + } |
2566 | 2577 | break; |
2567 | 2578 | } |
2568 | 2579 | } |
|