[Python-ideas] Fixed point format for numbers with locale based separators

Barry Scott barry at barrys-emacs.org
Sat Jan 5 04:32:16 EST 2019


On Friday, 4 January 2019 14:57:53 GMT Łukasz Stelmach wrote:
> Hi,
> 
> I would like to present two pull requests[1][2] implementing fixed point
> presentation of numbers and ask for comments. The first is mine. I
> learnt about the second after publishing mine.
> 
> The only format using decimal separator from locale data for
> float/complex/decimal numbers at the moment is "n" which behaves like
> "g". The drawback of these formats, I would like to overcome, is the
> inability to print numbers ranging more than one order of magnitude with
> the same number of decimal digits without "manually" (with some additional
> custom code) adjusting precission. The other option is to "manually"
> replace "." as printed by "f" with a local decimal separator. Neither of
> these option is appealing to my.
> 
> Formatting 1.23456789 * n (LC_ALL=3Dpl_PL.UTF-8)
> 
>     | n |    ".2f" |    ".3n" |
>     |
>     |---+----------+----------|
>     |
>     | 1 |     1.23 |     1,23 |
>     | 2 |    12.35 |     12,3 |
>     | 3 |   123.46 |      123 |
>     | 4 |  1234.57 | 1,23e+03 |

Can you use locale.format_string() to solve this?

I used this to test:

import locale

n = 1.23456789
for order in range(5):
    m = n * (10**order)
    for lang in ('en_GB.utf8', 'pl_PL.utf8'):
        locale.setlocale(locale.LC_ALL, lang)
        print( 'python %%.2f in %s: %.2f' % (lang, m) )
        print( locale.format_string('locale %%.2f in %s: %.2f', (lang, m), 
grouping=True) )
    print()

Which outputs:
python %.2f in en_GB.utf8: 1.23
locale %.2f in en_GB.utf8: 1.23
python %.2f in pl_PL.utf8: 1.23
locale %.2f in pl_PL.utf8: 1,23

python %.2f in en_GB.utf8: 12.35
locale %.2f in en_GB.utf8: 12.35
python %.2f in pl_PL.utf8: 12.35
locale %.2f in pl_PL.utf8: 12,35

python %.2f in en_GB.utf8: 123.46
locale %.2f in en_GB.utf8: 123.46
python %.2f in pl_PL.utf8: 123.46
locale %.2f in pl_PL.utf8: 123,46

python %.2f in en_GB.utf8: 1234.57
locale %.2f in en_GB.utf8: 1,234.57
python %.2f in pl_PL.utf8: 1234.57
locale %.2f in pl_PL.utf8: 1 234,57

python %.2f in en_GB.utf8: 12345.68
locale %.2f in en_GB.utf8: 12,345.68
python %.2f in pl_PL.utf8: 12345.68
locale %.2f in pl_PL.utf8: 12 345,68

Barry





More information about the Python-ideas mailing list