How can I print a float with thousands separators?

后端 未结 3 904
南旧
南旧 2021-01-01 12:38

How can I format a decimal number so that 32757121.33 will display as 32.757.121,33?

相关标签:
3条回答
  • 2021-01-01 13:13

    Use locale.format():

    >>> import locale
    >>> locale.setlocale(locale.LC_ALL, 'German')
    'German_Germany.1252'
    >>> print(locale.format('%.2f', 32757121.33, True))
    32.757.121,33
    

    You can restrict the locale changes to the display of numeric values (when using locale.format(), locale.str() etc.) and leave other locale settings unaffected:

    >>> locale.setlocale(locale.LC_NUMERIC, 'English')
    'English_United States.1252'
    >>> print(locale.format('%.2f', 32757121.33, True))
    32,757,121.33
    >>> locale.setlocale(locale.LC_NUMERIC, 'German')
    'German_Germany.1252'
    >>> print(locale.format('%.2f', 32757121.33, True))
    32.757.121,33
    
    0 讨论(0)
  • 2021-01-01 13:21

    If you can't or don't want to use locale for some reason, you can also do it with a regular expression:

    import re
    def sep(s, thou=",", dec="."):
        integer, decimal = s.split(".")
        integer = re.sub(r"\B(?=(?:\d{3})+$)", thou, integer)
        return integer + dec + decimal
    

    sep() takes the string representation of a standard Python float and returns it with custom thousands and decimal separators.

    >>> s = "%.2f" % 32757121.33
    >>> sep(s)
    '32,757,121.33'
    >>> sep(s, thou=".", dec=",")
    '32.757.121,33'
    

    Explanation:

    \B      # Assert that we're not at the start of the number
    (?=     # Match at a position where it's possible to match...
     (?:    #  the following regex:
      \d{3} #   3 digits
     )+     #  repeated at least once
     $      #  until the end of the string
    )       # (thereby ensuring a number of digits divisible by 3
    
    0 讨论(0)
  • 2021-01-01 13:35

    I have found another solution:

    '{:,.2f}'.format(num).replace(".","%").replace(",",".").replace("%",",")
    
    0 讨论(0)
提交回复
热议问题