货币在Python中的格式

我正在寻找格式化数字188518982.18到188,518,982.18英镑使用Python。

我该怎么做?

请参阅区域设置模块。

这是货币(和date)格式。

 >>> 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中的新function

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

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

不知道为什么没有提到更多的在线(或在这个线程上),但Edgewall家伙的Babel包(和Django实用程序)对于货币格式化(以及许多其他i18n任务)非常棒。 这很好,因为它不需要像核心Python语言环境模块一样在全局范围内执行所有操作。

OP给出的例子就是:

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

我的语言环境设置似乎不完整,所以我也看到超出这个答案,发现:

http://docs.python.org/library/decimal.html#recipes

独立操作系统

只是想在这里分享。

如果您正在使用OSX并且尚未设置您的语言环境模块设置,则第一个答案将不起作用,您将收到以下错误:

 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. 

要解决这个问题,你将不得不使用以下方法:

 locale.setlocale(locale.LC_ALL, 'en_US') 

这是一个古老的post,但我刚刚实施了以下解决scheme:

  • 不需要外部模块
  • 不需要创build一个新的function
  • 可以在线完成
  • 处理多个variables
  • 处理负面美元金额

码:

 num1 = 4153.53 num2 = -23159.398598 print 'This: ${:0,.0f} and this: ${:0,.2f}'.format(num1, num2).replace('$-','-$') 

输出:

 This: $4,154 and this: -$23,159.40 

而对于原来的海报,显然,只需将$ £

哦,这是一个有趣的野兽。

我已经花了相当多的时间来解决这个问题,有三个主要的问题不同于区域设置和区域设置: – 货币符号和方向 – 千位分隔符 – 小数点

我已经写了我自己相当广泛的实现这是猕猴桃python框架的一部分,请检查LGPL:ed来源在这里:

http://svn.async.com.br/cgi-bin/viewvc.cgi/kiwi/trunk/kiwi/currency.py?view=markup

该代码略为Linux / Glibc具体,但不应该太难以采用Windows或其他Unix。

一旦你安装了,你可以做到以下几点:

 >>> from kiwi.datatypes import currency >>> v = currency('10.5').format() 

哪个会给你:

 '$10.50' 

要么

 '10,50 kr' 

取决于当前select的区域设置。

这篇文章的主要观点是,它可以使用老版本的python。 locale.currency是在Python 2.5中引入的。

我来看看同样的事情,发现python钱还没有真正使用它,但也许两者的组合会很好

一个lambda用于在函数内部计算它,来自@Nate的答案

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

接着,

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

#打印variables'Total:',格式如下:'9,348.237'

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

在这种情况下,“{:7,.3f}”格式化数字的空间数量是百万,并带有3个小数点。 然后添加'.format(zum1)。 zum1是在我的特定程序中有所有数字的总和的大数的variables。 variables可以是你决定使用的任何东西。