Localized decimal numbers format

Viewed 119

I want to print a number in a localized format with a thousands separator and two decimal digits.

import locale
locale.setlocale(locale.LC_ALL, 'pl_PL.UTF-8')

value = 12345.12356

print(f'{value:,.2f}')
print(f'{value:n}')

Output:

12,345.12
12 345,1

The second string is almost what I want, but I cannot find a way to define precision. Cannot use

print(f'{value:,.2n}')

Traceback (most recent call last):
  File "x.py", line 8, in <module>
    print(f'{value:,.2n}')
ValueError: Cannot specify ',' with 'n'.

while this gives an unexpected result:

print(f'{value:.2n}')

1,2e+04

How to set the precision to two digits?

Note, I know I can replace the characters in 12,345.12 or use the decimal module etc. I just want to know if I can't interpret the documentation correctly, or if the Python developers didn't foresee this need. The latter would be an unpleasant surprise.

1 Answers

You can try this:

import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'

value = 12345.12356

print(locale.format_string("%.2f", value, grouping=True))

Output: 12,345.12

OR

import locale
from babel import numbers

value = 12345.12356

val = numbers.format_decimal(value, locale='pl_PL')
print (val)

Output: 12 345,124

Related