gh-87790: support thousands separators for formatting fractional part of floats (#125304)

```pycon
>>> f"{123_456.123_456:_._f}"  # Whole and fractional
'123_456.123_456'
>>> f"{123_456.123_456:_f}"    # Integer component only
'123_456.123456'
>>> f"{123_456.123_456:._f}"   # Fractional component only
'123456.123_456'
>>> f"{123_456.123_456:.4_f}"  # with precision
'123456.1_235'
```
This commit is contained in:
Sergey B Kirpichev 2025-02-25 18:27:07 +03:00 committed by GitHub
parent fa6a8140dd
commit f39a07be47
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 218 additions and 45 deletions

View file

@ -9772,7 +9772,8 @@ _PyUnicode_InsertThousandsGrouping(
Py_ssize_t min_width,
const char *grouping,
PyObject *thousands_sep,
Py_UCS4 *maxchar)
Py_UCS4 *maxchar,
int forward)
{
min_width = Py_MAX(0, min_width);
if (writer) {
@ -9809,14 +9810,14 @@ _PyUnicode_InsertThousandsGrouping(
should be an empty string */
assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
digits_pos = d_pos + n_digits;
digits_pos = d_pos + (forward ? 0 : n_digits);
if (writer) {
buffer_pos = writer->pos + n_buffer;
buffer_pos = writer->pos + (forward ? 0 : n_buffer);
assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
}
else {
buffer_pos = n_buffer;
buffer_pos = forward ? 0 : n_buffer;
}
if (!writer) {
@ -9838,7 +9839,7 @@ _PyUnicode_InsertThousandsGrouping(
digits, &digits_pos,
n_chars, n_zeros,
use_separator ? thousands_sep : NULL,
thousands_sep_len, maxchar);
thousands_sep_len, maxchar, forward);
/* Use a separator next time. */
use_separator = 1;
@ -9867,7 +9868,7 @@ _PyUnicode_InsertThousandsGrouping(
digits, &digits_pos,
n_chars, n_zeros,
use_separator ? thousands_sep : NULL,
thousands_sep_len, maxchar);
thousands_sep_len, maxchar, forward);
}
return count;
}