How to force dot on thousands separator?

9.5k views Asked by At

I already saw a lot of question teaching how easy is to do it with comma as thousands separator:

>>> format(1123000,',d')
'1,123,000'

But if I try to use a dot, it goes nuts:

>>> format(1123000,'.d')
ValueError: Format specifier missing precision

Is there a simple Python built-in locale independent way to make it output '1.123.000' instead of '1,123,000'?

I already found this answer on Add 'decimal-mark' thousands separators to a number but it manually do it. Can it be simpler as format(1123000,'.d') and locale independent? Or Python does not provide it built-in?

@Eugene Yarmash Using itertools can give you some more flexibility:

>>> from itertools import zip_longest
>>> num = "1000000"
>>> sep = "."
>>> places = 3
>>> args = [iter(num[::-1])] * places
>>> sep.join("".join(x) for x in zip_longest(*args, fillvalue=""))[::-1]
'1.000.000'
2

There are 2 answers

1
James On BEST ANSWER

If you are only dealing with integers, you can use:

x = 123456789
'{:,}'.format(x).replace(',','.')
# returns
'123.456.789'
0
Nicolas On

and if you want to add some decimals (e.g.: 2), you can just chain a few replace operations:

x = 123456789.123456789
'{:,.2f}'.format(x).replace(',','*').replace('.', ',').replace('*','.')
>>> '123.456.789,12'