-2

在 python 中是否有一种简单的方法可以用逗号格式化数字,即 11222.33 将打印为:$11,222.33。

目前我正在做类似的事情:

def formatMoney(number):
    res = str(number)

    # Number of digits before decimal
    n = res.find('.')
    n = n if (n >= 0) else len(res)
    if n < 4:
        return res[:n+3]

    # Location of first comma
    start = n % 3
    start = start if (start > 0) else 3

    # Break into parts
    parts = [res[:start]]
    parts += [res[i:i+3] for i in range(start, n - 3, 3)]
    # Last part includes 3 digits before decimal and 2 after
    parts += [res[n-3:n+3]]

    return ",".join(parts)

但我觉得我必须在这里重新发明轮子。我错过了标准库中的一个包,还是一个更明显的方法?

4

2 回答 2

3
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
print(locale.currency(11222.33, grouping=True))

产量

$11,222.33

en_US.UTF-8当然,这只是一个例子。

在 Unix 上,您可以运行

% locale -a

查看您的机器上有哪些可用的语言环境。不幸的是,我不知道 Windows 等价物是什么。


import subprocess
import locale
proc = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE)
out, err = proc.communicate()
for name in out.splitlines():
    locale.setlocale(locale.LC_ALL, name)
    try:
        currency = locale.currency(11222.33, grouping=True)
        print('{}: {}'.format(name, currency))
    except ValueError: pass

产量(取决于您机器上安装的语言环境,例如):

el_CY.utf8: 11.222,33€
el_GR.utf8: 11.222,33€
en_AG: $11,222.33
en_AG.utf8: $11,222.33
en_AU.utf8: $11,222.33
en_BW.utf8: Pu11,222.33
en_CA.utf8: $11,222.33
en_DK.utf8: kr 11.222,33
en_GB.utf8: £11,222.33
en_HK.utf8: HK$11,222.33
en_IE.utf8: €11,222.33
en_IN: ₹ 11,222.33
en_IN.utf8: ₹ 11,222.33
en_NG: ₦11,222.33
en_NG.utf8: ₦11,222.33
en_NZ.utf8: $11,222.33
en_PH.utf8: Php11,222.33
en_SG.utf8: $11,222.33
en_US.utf8: $11,222.33
en_ZA.utf8: R11,222.33
en_ZM: K11,222.33
en_ZM.utf8: K11,222.33
en_ZW.utf8: Z$11,222.33
tr_TR.utf8: 11.222,33 YTL
于 2013-10-07T19:57:54.173 回答
3

使用.format()

>>> a = 11222.33
>>> "${:,.2f}".format(a)
'$11,222.33'
>>> a = 111111111222.33
>>> "${:,.2f}".format(a)
'$111,111,111,222.33'
>>>
于 2013-10-07T19:59:18.013 回答