Currency formatting in Python

2019-01-01 10:54发布

I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.

How can I do this?

11条回答
泛滥B
2楼-- · 2019-01-01 11:04

If you are using OSX and have yet to set your locale module setting this first answer will not work you will receive the following error:

Traceback (most recent call last):File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 221, in currency
raise ValueError("Currency formatting is not possible using "ValueError: Currency formatting is not possible using the 'C' locale.

To remedy this you will have to do use the following:

locale.setlocale(locale.LC_ALL, 'en_US')
查看更多
无与为乐者.
3楼-- · 2019-01-01 11:05

#printing the variable 'Total:' in a format that looks like this '9,348.237'

print ('Total:',   '{:7,.3f}'.format(zum1))

where the '{:7,.3f}' es the number of spaces for formatting the number in this case is a million with 3 decimal points. Then you add the '.format(zum1). The zum1 is tha variable that has the big number for the sum of all number in my particular program. Variable can be anything that you decide to use.

查看更多
回忆,回不去的记忆
4楼-- · 2019-01-01 11:05

A lambda for calculating it inside a function, with help from @Nate's answer

converter = lambda amount, currency: "%s%s%s" %(
    "-" if amount < 0 else "", 
    currency, 
    ('{:%d,.2f}'%(len(str(amount))+3)).format(abs(amount)).lstrip())

and then,

>>> converter(123132132.13, "$")
'$123,132,132.13'

>>> converter(-123132132.13, "$")
'-$123,132,132.13'
查看更多
浮光初槿花落
5楼-- · 2019-01-01 11:11

Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.

The example the OP gave would simply be:

>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18
查看更多
孤独寂梦人
6楼-- · 2019-01-01 11:16

I've come to look at the same thing and found python-money not really used it yet but maybe a mix of the two would be good

查看更多
还给你的自由
7楼-- · 2019-01-01 11:18

See the locale module.

This does currency (and date) formatting.

>>> import locale
>>> locale.setlocale( locale.LC_ALL, '' )
'English_United States.1252'
>>> locale.currency( 188518982.18 )
'$188518982.18'
>>> locale.currency( 188518982.18, grouping=True )
'$188,518,982.18'
查看更多
登录 后发表回答