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 /Objects | |
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 'Objects')
-rw-r--r-- | Objects/bytesobject.c | 11 | ||||
-rw-r--r-- | Objects/unicodeobject.c | 8 |
2 files changed, 13 insertions, 6 deletions
diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c index 78c42c2..d0124c0 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -415,6 +415,7 @@ formatfloat(PyObject *v, int flags, int prec, int type, PyObject *result; double x; size_t len; + int dtoa_flags = 0; x = PyFloat_AsDouble(v); if (x == -1.0 && PyErr_Occurred()) { @@ -426,8 +427,13 @@ formatfloat(PyObject *v, int flags, int prec, int type, if (prec < 0) prec = 6; - p = PyOS_double_to_string(x, type, prec, - (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL); + if (flags & F_ALT) { + dtoa_flags |= Py_DTSF_ALT; + } + if (flags & F_NO_NEG_0) { + dtoa_flags |= Py_DTSF_NO_NEG_0; + } + p = PyOS_double_to_string(x, type, prec, dtoa_flags, NULL); if (p == NULL) return NULL; @@ -706,6 +712,7 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len, case ' ': flags |= F_BLANK; continue; case '#': flags |= F_ALT; continue; case '0': flags |= F_ZERO; continue; + case 'z': flags |= F_NO_NEG_0; continue; } break; } diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index 1b2f332..c665f57 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -14372,7 +14372,7 @@ formatfloat(PyObject *v, struct unicode_format_arg_t *arg, double x; Py_ssize_t len; int prec; - int dtoa_flags; + int dtoa_flags = 0; x = PyFloat_AsDouble(v); if (x == -1.0 && PyErr_Occurred()) @@ -14383,9 +14383,9 @@ formatfloat(PyObject *v, struct unicode_format_arg_t *arg, prec = 6; if (arg->flags & F_ALT) - dtoa_flags = Py_DTSF_ALT; - else - dtoa_flags = 0; + dtoa_flags |= Py_DTSF_ALT; + if (arg->flags & F_NO_NEG_0) + dtoa_flags |= Py_DTSF_NO_NEG_0; p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL); if (p == NULL) return -1; |