Python中的货币格式

2024-04-25 01:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

不太清楚为什么没有在网上(或这个线程上)更多地提到它,但是Edgewall的人提供的Babel包(和Django实用程序)对于货币格式化(以及许多其他i18n任务)来说是非常棒的。这很好,因为它不需要像核心Python语言环境模块那样做任何全局性的事情。

OP给出的例子很简单:

>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18

请参阅locale模块。

这将进行货币(和日期)格式设置。

>>> 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'

2.7中的新功能

>>> '{:20,.2f}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'

http://docs.python.org/dev/whatsnew/2.7.html#pep-0378

相关问题 更多 >