Skip to content

Commit

Permalink
Issue #22090: Fix '%' formatting for infinities and NaNs.
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan Krah committed Aug 26, 2014
1 parent d84fd73 commit 298131a
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
2 changes: 2 additions & 0 deletions Lib/decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3769,6 +3769,8 @@ def __format__(self, specifier, context=None, _localeconv=None):
if self._is_special:
sign = _format_sign(self._sign, spec)
body = str(self.copy_abs())
if spec['type'] == '%':
body += '%'
return _format_align(sign, body, spec)

# a type of None defaults to 'g' or 'G', depending on context
Expand Down
5 changes: 5 additions & 0 deletions Lib/test/test_decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1057,6 +1057,11 @@ def test_formatting(self):

# issue 6850
('a=-7.0', '0.12345', 'aaaa0.1'),

# issue 22090
('<^+15.20%', 'inf', '<<+Infinity%<<<'),
('\x07>,%', 'sNaN1234567', 'sNaN1234567%'),
('=10.10%', 'NaN123', ' NaN123%'),
]
for fmt, d, result in test_values:
self.assertEqual(format(Decimal(d), fmt), result)
Expand Down
11 changes: 7 additions & 4 deletions Modules/_decimal/libmpdec/io.c
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ _mpd_to_string(char **result, const mpd_t *dec, int flags, mpd_ssize_t dplace)

if (mpd_isspecial(dec)) {

mem = sizeof "-Infinity";
mem = sizeof "-Infinity%";
if (mpd_isnan(dec) && dec->len > 0) {
/* diagnostic code */
mem += dec->digits;
Expand Down Expand Up @@ -609,10 +609,10 @@ _mpd_to_string(char **result, const mpd_t *dec, int flags, mpd_ssize_t dplace)
*cp++ = (flags&MPD_FMT_UPPER) ? 'E' : 'e';
cp = exp_to_string(cp, ldigits-dplace);
}
}

if (flags&MPD_FMT_PERCENT) {
*cp++ = '%';
}
if (flags&MPD_FMT_PERCENT) {
*cp++ = '%';
}

assert(cp < decstring+mem);
Expand Down Expand Up @@ -1260,6 +1260,9 @@ mpd_qformat_spec(const mpd_t *dec, const mpd_spec_t *spec,
stackspec.align = '>';
spec = &stackspec;
}
if (type == '%') {
flags |= MPD_FMT_PERCENT;
}
}
else {
uint32_t workstatus = 0;
Expand Down

0 comments on commit 298131a

Please sign in to comment.