diff options
author | Cédric Krier <cedk@users.noreply.github.com> | 2021-04-12 12:17:40 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-04-12 12:17:40 (GMT) |
commit | e126547c070fbc080562abb08e16a2c93a8a805d (patch) | |
tree | ec2d7f22999855aa870d69891fb476106f2b9fe0 /Lib/locale.py | |
parent | 95bbb331ecb3ef5d05859d90b287cc3d27613c86 (diff) | |
download | cpython-e126547c070fbc080562abb08e16a2c93a8a805d.zip cpython-e126547c070fbc080562abb08e16a2c93a8a805d.tar.gz cpython-e126547c070fbc080562abb08e16a2c93a8a805d.tar.bz2 |
bpo-34311: Add locale.localize (GH-15275)
* Add method localize to the locale module
* Update the documentation of the locale module
Diffstat (limited to 'Lib/locale.py')
-rw-r--r-- | Lib/locale.py | 16 |
1 files changed, 13 insertions, 3 deletions
diff --git a/Lib/locale.py b/Lib/locale.py index ee841e8..6d4f519 100644 --- a/Lib/locale.py +++ b/Lib/locale.py @@ -185,8 +185,14 @@ def _format(percent, value, grouping=False, monetary=False, *additional): formatted = percent % ((value,) + additional) else: formatted = percent % value + if percent[-1] in 'eEfFgGdiu': + formatted = _localize(formatted, grouping, monetary) + return formatted + +# Transform formatted as locale number according to the locale settings +def _localize(formatted, grouping=False, monetary=False): # floats and decimal ints need special action! - if percent[-1] in 'eEfFgG': + if '.' in formatted: seps = 0 parts = formatted.split('.') if grouping: @@ -196,7 +202,7 @@ def _format(percent, value, grouping=False, monetary=False, *additional): formatted = decimal_point.join(parts) if seps: formatted = _strip_padding(formatted, seps) - elif percent[-1] in 'diu': + else: seps = 0 if grouping: formatted, seps = _group(formatted, monetary=monetary) @@ -267,7 +273,7 @@ def currency(val, symbol=True, grouping=False, international=False): raise ValueError("Currency formatting is not possible using " "the 'C' locale.") - s = _format('%%.%if' % digits, abs(val), grouping, monetary=True) + s = _localize(f'{abs(val):.{digits}f}', grouping, monetary=True) # '<' and '>' are markers if the sign must be inserted between symbol and value s = '<' + s + '>' @@ -323,6 +329,10 @@ def delocalize(string): string = string.replace(dd, '.') return string +def localize(string, grouping=False, monetary=False): + """Parses a string as locale number according to the locale settings.""" + return _localize(string, grouping, monetary) + def atof(string, func=float): "Parses a string as a float according to the locale settings." return func(delocalize(string)) |