Search code examples
pythonformatlocalenumber-formattingdigit-separator

Add 'decimal-mark' thousands separators to a number


How do I format 1000000 to 1.000.000 in Python? where the '.' is the decimal-mark thousands separator.


Solution

  • If you want to add a thousands separator, you can write:

    >>> '{0:,}'.format(1000000)
    '1,000,000'
    

    But it only works in Python 2.7 and above.

    See format string syntax.

    In older versions, you can use locale.format():

    >>> import locale
    >>> locale.setlocale(locale.LC_ALL, '')
    'en_AU.utf8'
    >>> locale.format('%d', 1000000, 1)
    '1,000,000'
    

    the added benefit of using locale.format() is that it will use your locale's thousands separator, e.g.

    >>> import locale
    >>> locale.setlocale(locale.LC_ALL, 'de_DE.utf-8')
    'de_DE.utf-8'
    >>> locale.format('%d', 1000000, 1)
    '1.000.000'