Python 中的货币格式
- 2025-01-14 08:50:00
- admin 原创
- 119
问题描述:
我希望使用 Python 将 188518982.18 这样的数字格式化为 £188,518,982.18。
我怎样才能做到这一点?
解决方案 1:
参见语言环境模块。
这执行货币(和日期)格式化。
>>> 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:
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
解决方案 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
解决方案 4:
这是一个古老的帖子,但我刚刚实施了以下解决方案:
不需要外部模块
不需要创建新函数
可以在线完成
处理多个变量
处理负美元金额
代码:
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
对于原始海报,显然只需切换$
为£
解决方案 5:
"{:0,.2f}".format(float(your_numeric_value))
在 Python 3 中可以完成这个工作;它给出类似以下几行的内容:
10,938.29
10,899.00
10,898.99
2,328.99
解决方案 6:
我的区域设置似乎不完整,因此我不得不仔细查看这个 SO 答案并发现:
http://docs.python.org/library/decimal.html#recipes
独立于操作系统
只是想在这里分享。
解决方案 7:
如果您使用的是 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')
解决方案 8:
如果我是你,我会使用 BABEL:http://babel.pocoo.org/en/latest/index.html
from babel.numbers import format_decimal
format_decimal(188518982.18, locale='en_US')
解决方案 9:
这里已经有十几个解决方案,但我认为下面的解决方案是最好的,因为:
这很简单
遵循操作系统区域设置
不需要外部库
你可以让它简洁
我的解决方案是使用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)
将在配置为巴西葡萄牙语的Windows 10 中输出:
R$ 1.346.896,67
它有点冗长,所以如果你经常使用它,最好预定义一些参数并使用更短的名称,然后在 f 字符串中使用它:
fmt = lambda x: locale.currency(x, grouping=True, symbol=True)
print(f"Value: {fmt(1346896.67444)}"
您可以为该方法传递一个语言环境值setlocale
,但其值取决于操作系统,因此请小心。如果您使用的是 *nix 服务器,您还需要检查所需的语言环境是否已正确安装在操作系统中。
您也可以关闭符号传递symbol=False
。
解决方案 10:
哦,那是一只有趣的野兽。
我花了相当多的时间来解决这个问题,有三个主要问题因语言环境而异: - 货币符号和方向 - 千位分隔符 - 小数点
我已经编写了自己相当广泛的实现,它是 kiwi 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'
取决于当前选择的区域设置。
这篇文章相对于其他文章的主要特点是它可以与旧版本的 Python 一起使用。locale.currency 是在 Python 2.5 中引入的。
解决方案 11:
以如下格式打印变量“Total:”:“9,348.237”
print ('Total:', '{:7,.3f}'.format(zum1))
其中 '{:7,.3f}' 是格式化数字的空格数,在本例中是一百万,带有 3 个小数点。然后添加 '.format(zum1)。zum1 是变量,它包含我特定程序中所有数字的总和。变量可以是您决定使用的任何内容。
解决方案 12:
受到上述代码的启发:D
def money_format(value):
value = str(value).split('.')
money = ''
count = 1
for digit in value[0][::-1]:
if count != 3:
money += digit
count += 1
else:
money += f'{digit},'
count = 1
if len(value) == 1:
money = ('$' + money[::-1]).replace('$-','-$')
else:
money = ('$' + money[::-1] + '.' + value[1]).replace('$-','-$')
return money
解决方案 13:
在@Nate 的回答的帮助下,使用 lambda 在函数内部进行计算
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'
解决方案 14:
简单的 Python 代码!
def format_us_currency(value):
value=str(value)
if value.count(',')==0:
b,n,v='',1,value
value=value[:value.rfind('.')]
for i in value[::-1]:
b=','+i+b if n==3 else i+b
n=1 if n==3 else n+1
b=b[1:] if b[0]==',' else b
value=b+v[v.rfind('.'):]
return '$'+(value.rstrip('0').rstrip('.') if '.' in value else value)
解决方案 15:
仅使用 Python 标准库导入,这是一种定义自定义格式的紧凑方法:
>>> from functools import partial
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # or whatever locale you want
>>> _c = partial(locale.currency, grouping=True)
>>> my_amount = 188518982.18
>>> print(f'{_c(my_amount)}')
$188,518,982.18
解决方案 16:
简单方法:
安装 bable 包:pip install babel
创建currency.py 文件并...
从 babel.numbers 导入 format_currency
def format_currency_brl(值):返回 format_currency(值,'BRL',locale='pt_BR')
非常有效......
解决方案 17:
Python 有关于如何格式化字符串的详细帮助部分help("FORMATTING")
。不过,其中一些功能仅在较新版本的 Python 中可用。以下是我的做法:
def _formatted_len(s: float, decimals: int = 2, sign: str = "-"):
"""
Figure out the length of the string representation of s
that includes commas, decimal point, decimals, and sign (if any)
"""
formatted_s = f"{s:{sign},.{decimals}f}"
return len(formatted_s)
def currency(x: float, symbol: str = "$", decimals: int = 2, sign: str = "-"):
"""
Format the number `x` as a currency.
Args:
x: The numerical value of the currency
symbol: The currency symbol (e.g. $, £, etc.)
decimals: How many digits to include after the decimal point
sign: How to sign the value, options are:
'+': uses a sign for both positive and negative values
'-': uses a sign for negative values only
' ': sign negative numbers and leave a blank space if positive
Returns:
A string representing the currency
"""
assert len(symbol) == 1
assert sign in ["-", "+", " "]
length = _formatted_len(x, decimals, sign)
return f"{x:{symbol}={sign}{length + 1},.{decimals}f}"
print(currency(1234.567, sign=" "))
print(currency(-3000.1234, decimals=3, sign="+"))
print(currency(1e4, symbol="£", decimals=0, sign="-"))
输出:
$1,234.57
-$3,000.123
£10,000