How can I print a float with thousands separators?

后端 未结 3 903
南旧
南旧 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
    

提交回复
热议问题