使用逗号格式化数字字符串以显示货币类型

时间:2013-10-07 19:54:10

标签: python

在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)

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

使用.format()

>>> a = 11222.33
>>> "${:,.2f}".format(a)
'$11,222.33'
>>> a = 111111111222.33
>>> "${:,.2f}".format(a)
'$111,111,111,222.33'
>>>