Rai*_*Son 140 python formatting currency
我想用Python将188518982.18这样的数字格式化为188,518,982.18英镑.
我怎样才能做到这一点?
S.L*_*ott 191
请参阅区域设置模块.
这样做了货币(和日期)格式.
>>> 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'
Run Code Online (Sandbox Code Playgroud)
nat*_*e c 89
>>> '{:20,.2f}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'
Run Code Online (Sandbox Code Playgroud)
http://docs.python.org/dev/whatsnew/2.7.html#pep-0378
gle*_*enc 40
不太清楚为什么它没有在网上(或在这个帖子上)被提及,但来自Edgewall家伙的Babel软件包(和Django实用程序)对于货币格式化(以及许多其他i18n任务)来说非常棒.这很好,因为它不需要像核心Python语言环境模块那样全局地做所有事情.
OP给出的例子就是:
>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18
Run Code Online (Sandbox Code Playgroud)
elP*_*tor 25
这是一篇古老的文章,但我刚刚实施了以下解决方案:
码:
num1 = 4153.53
num2 = -23159.398598
print 'This: ${:0,.0f} and this: ${:0,.2f}'.format(num1, num2).replace('$-','-$')
Run Code Online (Sandbox Code Playgroud)
输出:
This: $4,154 and this: -$23,159.40
Run Code Online (Sandbox Code Playgroud)
而对于原来的海报,很明显,只要切换$为£
Eug*_*pov 18
"{:0,.2f}".format(float(your_numeric_value))在 Python 3 中完成这项工作;它给出了类似于以下几行之一的内容:
10,938.29
10,899.00
10,898.99
2,328.99
Run Code Online (Sandbox Code Playgroud)
use*_*986 16
我的语言环境设置似乎不完整,所以我也超越了这个SO答案,发现:
http://docs.python.org/library/decimal.html#recipes
独立操作系统
只是想在这里分享.
nev*_*ves 10
这里已经有十几种解决方案,但我相信下面的解决方案是最好的,因为:
我的解决方案是使用locale.currency()方法:
import locale
# this sets locale to the current Operating System value
locale.setlocale(locale.LC_ALL, '')
print(locale.currency(1346896.67444, grouping=True, symbol=True)
Run Code Online (Sandbox Code Playgroud)
将在配置为巴西葡萄牙语的 Windows 10 中输出:
R$ 1.346.896,67
Run Code Online (Sandbox Code Playgroud)
它有点冗长,所以如果您经常使用它,也许最好预定义一些参数并使用较短的名称并在 f 字符串内使用它:
fmt = lambda x: locale.currency(x, grouping=True, symbol=True)
print(f"Value: {fmt(1346896.67444)}"
Run Code Online (Sandbox Code Playgroud)
您可以传递该方法的区域设置值setlocale,但其值取决于操作系统,因此请注意。如果您使用的是 *nix 服务器,您还需要检查操作系统中是否正确安装了所需的语言环境。
您还可以关闭符号传递symbol=False。
如果您正在使用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.
Run Code Online (Sandbox Code Playgroud)
要解决此问题,您必须使用以下内容:
locale.setlocale(locale.LC_ALL, 'en_US')
Run Code Online (Sandbox Code Playgroud)
小智 7
如果我是你,我会使用 BABEL:http : //babel.pocoo.org/en/latest/index.html
from babel.numbers import format_decimal
format_decimal(188518982.18, locale='en_US')
Run Code Online (Sandbox Code Playgroud)