Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions 4 Doc/library/string.rst
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,10 @@ The available presentation types for floating point and decimal values are:
| | ``'E'`` if the number gets too large. The |
| | representations of infinity and NaN are uppercased, too. |
+---------+----------------------------------------------------------+
| ``'m'`` | Number. This is the same as ``'f'``, except that it uses |
| | the current locale setting to insert the appropriate |
| | number separator characters. |
+---------+----------------------------------------------------------+
| ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
| | the current locale setting to insert the appropriate |
| | number separator characters. |
Expand Down
11 changes: 6 additions & 5 deletions 11 Lib/_pydecimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3746,7 +3746,7 @@ def __format__(self, specifier, context=None, _localeconv=None):

The specifier should be a standard format specifier, with the
form described in PEP 3101. Formatting types 'e', 'E', 'f',
'F', 'g', 'G', 'n' and '%' are supported. If the formatting
'F', 'g', 'G', 'm', 'n' and '%' are supported. If the formatting
type is omitted it defaults to 'g' or 'G', depending on the
value of context.capitals.
"""
Expand Down Expand Up @@ -6154,7 +6154,7 @@ def _convert_for_comparison(self, other, equality_op=False):
(?P<minimumwidth>(?!0)\d+)?
(?P<thousands_sep>,)?
(?:\.(?P<precision>0|(?!0)\d+))?
(?P<type>[eEfFgGn%])?
(?P<type>[eEfFgGmn%])?
\Z
""", re.VERBOSE|re.DOTALL)

Expand Down Expand Up @@ -6229,14 +6229,15 @@ def _parse_format_specifier(format_spec, _localeconv=None):

# determine thousands separator, grouping, and decimal separator, and
# add appropriate entries to format_dict
if format_dict['type'] == 'n':
if format_dict['type'] in ('m', 'n'):
# apart from separators, 'n' behaves just like 'g'
format_dict['type'] = 'g'
# and 'm' like 'f'
format_dict['type'] = 'g' if format_dict['type'] == 'n' else 'f'
if _localeconv is None:
_localeconv = _locale.localeconv()
if format_dict['thousands_sep'] is not None:
raise ValueError("Explicit thousands separator conflicts with "
"'n' type in format specifier: " + format_spec)
"'m' or 'n' type in format specifier: " + format_spec)
format_dict['thousands_sep'] = _localeconv['thousands_sep']
format_dict['grouping'] = _localeconv['grouping']
format_dict['decimal_point'] = _localeconv['decimal_point']
Expand Down
1 change: 1 addition & 0 deletions 1 Lib/test/test_decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,7 @@ def test_formatting(self):
('g', '0E-7', '0e-7'),
('g', '-0E2', '-0e+2'),
('.0g', '3.14159265', '3'), # 0 sig fig -> 1 sig fig
('.0m', '3.14159265', '3'), # same for 'm'
('.0n', '3.14159265', '3'), # same for 'n'
('.1g', '3.14159265', '3'),
('.2g', '3.14159265', '3.1'),
Expand Down
2 changes: 1 addition & 1 deletion 2 Lib/test/test_float.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ def test_format(self):
# in particular int specifiers
for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
[chr(x) for x in range(ord('A'), ord('Z')+1)]):
if not format_spec in 'eEfFgGn%':
if not format_spec in 'eEfFgGmn%':
self.assertRaises(ValueError, format, 0.0, format_spec)
self.assertRaises(ValueError, format, 1.0, format_spec)
self.assertRaises(ValueError, format, -1.0, format_spec)
Expand Down
5 changes: 5 additions & 0 deletions 5 Lib/test/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,11 @@ def test_locale(self):
self.assertIn(sep, text)
self.assertIn(point, text)
self.assertEqual(text.replace(sep, ''), '1234' + point + '5')

text = format(1234.5, ".3m")
self.assertIn(sep, text)
self.assertIn(point, text)
self.assertEqual(text.replace(sep, ''), '1234' + point + '500')
finally:
locale.setlocale(locale.LC_ALL, oldloc)

Expand Down
2 changes: 1 addition & 1 deletion 2 Lib/test/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ def test(f, format_spec, result):
# in particular int specifiers
for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
[chr(x) for x in range(ord('A'), ord('Z')+1)]):
if not format_spec in 'eEfFgGn%':
if not format_spec in 'eEfFgGmn%':
self.assertRaises(ValueError, format, 0.0, format_spec)
self.assertRaises(ValueError, format, 1.0, format_spec)
self.assertRaises(ValueError, format, -1.0, format_spec)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Introduce "m" formatter for float, complex and decimal numbers. It behaves
like "f" formatter but uses separators from locale data.
9 changes: 7 additions & 2 deletions 9 Modules/_decimal/libmpdec/io.c
Original file line number Diff line number Diff line change
Expand Up @@ -864,15 +864,20 @@ mpd_parse_fmt_str(mpd_spec_t *spec, const char *fmt, int caps)
*cp == 'G' || *cp == 'g' || *cp == '%') {
spec->type = *cp++;
}
else if (*cp == 'N' || *cp == 'n') {
else if (*cp == 'N' || *cp == 'n' ||
*cp == 'M' || *cp == 'm') {
/* locale specific conversion */
struct lconv *lc;
/* separator has already been specified */
if (*spec->sep) {
return 0;
}
spec->type = *cp++;
spec->type = (spec->type == 'N') ? 'G' : 'g';
if (spec->type == 'N' || spec->type == 'n') {
spec->type = (spec->type == 'N') ? 'G' : 'g';
} else {
spec->type = (spec->type == 'M') ? 'F' : 'f';
}
lc = localeconv();
spec->dot = lc->decimal_point;
spec->sep = lc->thousands_sep;
Expand Down
9 changes: 5 additions & 4 deletions 9 Modules/_decimal/tests/formathelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def rand_fillchar():

# Generate random format strings
# [[fill]align][sign][#][0][width][.precision][type]
def rand_format(fill, typespec='EeGgFfn%'):
def rand_format(fill, typespec='EeGgFfmn%'):
active = sorted(random.sample(range(7), random.randrange(8)))
have_align = 0
s = ''
Expand Down Expand Up @@ -277,7 +277,7 @@ def all_format_sep():
type = random.choice(('', 'E', 'e', 'G', 'g', 'F', 'f', '%'))
yield ''.join((fill, align, sign, zeropad, width, ',', prec, type))

# Partially brute force all possible format strings with an 'n' specifier.
# Partially brute force all possible format strings with an 'n' and 'm' specifiers.
# [[fill]align][sign][#][0][width][,][.precision][type]
def all_format_loc():
for align in ('', '<', '>', '=', '^'):
Expand All @@ -288,7 +288,8 @@ def all_format_loc():
if align != '': zeropad = ''
for width in ['']+[str(y) for y in range(1, 20)]+['101']:
for prec in ['']+['.'+str(y) for y in range(1, 20)]:
yield ''.join((fill, align, sign, zeropad, width, prec, 'n'))
for type in ('n', 'm'):
yield ''.join((fill, align, sign, zeropad, width, prec, type))

# Generate random format strings with a unicode fill character
# [[fill]align][sign][#][0][width][,][.precision][type]
Expand Down Expand Up @@ -338,5 +339,5 @@ def rand_locale():
elif elem == 4: # prec
s += '.'
s += str(random.randrange(100))
s += 'n'
s += random.choice('mn')
return s
11 changes: 10 additions & 1 deletion 11 Python/formatter_unicode.c
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,9 @@ format_float_internal(PyObject *value,
/* 'n' is the same as 'g', except for the locale used to
format the result. We take care of that later. */
type = 'g';
else if (type == 'm')
/* 'm' is for 'n', what 'f' is for 'g'. */
type = 'f';

val = PyFloat_AsDouble(value);
if (val == -1.0 && PyErr_Occurred())
Expand Down Expand Up @@ -1096,6 +1099,7 @@ format_float_internal(PyObject *value,
if (format->sign != '+' && format->sign != ' '
&& format->width == -1
&& format->type != 'n'
&& format->type != 'm'
&& !format->thousands_separators)
{
/* Fast path */
Expand Down Expand Up @@ -1125,7 +1129,7 @@ format_float_internal(PyObject *value,
parse_number(unicode_tmp, index, index + n_digits, &n_remainder, &has_decimal);

/* Determine the grouping, separator, and decimal point, if any. */
if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
if (get_locale_info(format->type == 'n' || format->type == 'm' ? LT_CURRENT_LOCALE :
format->thousands_separators,
&locale) == -1)
goto done;
Expand Down Expand Up @@ -1250,6 +1254,9 @@ format_complex_internal(PyObject *value,
/* 'n' is the same as 'g', except for the locale used to
format the result. We take care of that later. */
type = 'g';
else if (type == 'm')
/* 'm' is for 'n', what 'f' is for 'g'. */
type = 'f';

if (precision < 0)
precision = default_precision;
Expand Down Expand Up @@ -1542,6 +1549,7 @@ _PyFloat_FormatAdvancedWriter(_PyUnicodeWriter *writer,
case 'F':
case 'g':
case 'G':
case 'm':
case 'n':
case '%':
/* no conversion, already a float. do the formatting */
Expand Down Expand Up @@ -1581,6 +1589,7 @@ _PyComplex_FormatAdvancedWriter(_PyUnicodeWriter *writer,
case 'F':
case 'g':
case 'G':
case 'm':
case 'n':
/* no conversion, already a complex. do the formatting */
return format_complex_internal(obj, &format, writer);
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.