Search code examples
pythonformatlocalenumber-formattingdigit-separator

How to force dot on thousands separator?


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'

Solution

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

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