diff options
author | John Belmonte <john@neggie.net> | 2022-04-11 14:34:18 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-04-11 14:34:18 (GMT) |
commit | b0b836b20cb56c225874a4a39ef895f89ab2970f (patch) | |
tree | b333cd2e9ee95021e1fc3b45eee2da0b7ac0ee35 /Lib/_pydecimal.py | |
parent | dd207a6ac52d4bd9a71cf178fc1d5c17a6f07aff (diff) | |
download | cpython-b0b836b20cb56c225874a4a39ef895f89ab2970f.zip cpython-b0b836b20cb56c225874a4a39ef895f89ab2970f.tar.gz cpython-b0b836b20cb56c225874a4a39ef895f89ab2970f.tar.bz2 |
bpo-45995: add "z" format specifer to coerce negative 0 to zero (GH-30049)
Add "z" format specifier to coerce negative 0 to zero.
See https://github.com/python/cpython/issues/90153 (originally https://bugs.python.org/issue45995) for discussion.
This covers `str.format()` and f-strings. Old-style string interpolation is not supported.
Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
Diffstat (limited to 'Lib/_pydecimal.py')
-rw-r--r-- | Lib/_pydecimal.py | 9 |
1 files changed, 7 insertions, 2 deletions
diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py index f6d9ddf..89646fa 100644 --- a/Lib/_pydecimal.py +++ b/Lib/_pydecimal.py @@ -3795,6 +3795,10 @@ class Decimal(object): # represented in fixed point; rescale them to 0e0. if not self and self._exp > 0 and spec['type'] in 'fF%': self = self._rescale(0, rounding) + if not self and spec['no_neg_0'] and self._sign: + adjusted_sign = 0 + else: + adjusted_sign = self._sign # figure out placement of the decimal point leftdigits = self._exp + len(self._int) @@ -3825,7 +3829,7 @@ class Decimal(object): # done with the decimal-specific stuff; hand over the rest # of the formatting to the _format_number function - return _format_number(self._sign, intpart, fracpart, exp, spec) + return _format_number(adjusted_sign, intpart, fracpart, exp, spec) def _dec_from_triple(sign, coefficient, exponent, special=False): """Create a decimal instance directly, without any validation, @@ -6143,7 +6147,7 @@ _exact_half = re.compile('50*$').match # # A format specifier for Decimal looks like: # -# [[fill]align][sign][#][0][minimumwidth][,][.precision][type] +# [[fill]align][sign][z][#][0][minimumwidth][,][.precision][type] _parse_format_specifier_regex = re.compile(r"""\A (?: @@ -6151,6 +6155,7 @@ _parse_format_specifier_regex = re.compile(r"""\A (?P<align>[<>=^]) )? (?P<sign>[-+ ])? +(?P<no_neg_0>z)? (?P<alt>\#)? (?P<zeropad>0)? (?P<minimumwidth>(?!0)\d+)? |