问题:Python中的货币格式

我想使用Python将类似188518982.18的数字格式化为188,518,982.18英镑。

我怎样才能做到这一点?

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

How can I do this?


回答 0

请参阅语言环境模块。

这会进行货币(和日期)格式化。

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

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'

回答 1

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

New in 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


回答 2

不太确定为什么没有在网上(或在此主题中)提及更多,但是Babel Edgewall家伙包(和Django实用程序)对于货币格式(以及许多其他i18n任务)来说很棒。很好,因为它不需要像核心Python语言环境模块那样全局地做所有事情。

OP给出的示例仅是:

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

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

回答 3

这是一个古老的帖子,但是我只是实现了以下解决方案:

  • 不需要外部模块
  • 不需要创建新功能
  • 可以在线完成
  • 处理多个变量
  • 处理负的美元金额

码:

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

对于原始海报,显然,只需切换$£

This is an ancient post, but I just implemented the following solution which:

  • Doesn’t require external modules
  • Doesn’t require creating a new function
  • Can be done in-line
  • Handles multiple variables
  • Handles negative dollar amounts

Code:

num1 = 4153.53
num2 = -23159.398598

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

Output:

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

And for the original poster, obviously, just switch $ for £


回答 4

我的语言环境设置似乎不完整,所以我也没有看到这样的答案,而是发现:

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

与操作系统无关

只想在这里分享。

My locale settings seemed incomplete, so I had too look beyond this SO answer and found:

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

OS-independent

Just wanted to share here.


回答 5

如果您使用的是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')

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

回答 6

"{:0,.2f}".format(float(your_numeric_value))在Python 3中可以完成工作;它给出类似以下几行之一的内容:

10,938.29
10,899.00
10,898.99
2,328.99

"{:0,.2f}".format(float(your_numeric_value)) in Python 3 does the job; it gives out something like one of the following lines:

10,938.29
10,899.00
10,898.99
2,328.99

回答 7

如果我是你,我将使用BABEL:http : //babel.pocoo.org/en/latest/index.html

from babel.numbers import format_decimal


format_decimal(188518982.18, locale='en_US')

If I were you, I would use BABEL: http://babel.pocoo.org/en/latest/index.html

from babel.numbers import format_decimal


format_decimal(188518982.18, locale='en_US')

回答 8

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

我花了很多时间来解决这个问题,因地区而异的三个主要问题是:-货币符号和方向-千位分隔符-小数点

我已经编写了自己的相当广泛的实现,它是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中引入。

Oh, that’s an interesting beast.

I’ve spent considerable time of getting that right, there are three main issues that differs from locale to locale: – currency symbol and direction – thousand separator – decimal point

I’ve written my own rather extensive implementation of this which is part of the kiwi python framework, check out the LGPL:ed source here:

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

The code is slightly Linux/Glibc specific, but shouldn’t be too difficult to adopt to windows or other unixes.

Once you have that installed you can do the following:

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

Which will then give you:

'$10.50'

or

'10,50 kr'

Depending on the currently selected locale.

The main point this post has over the other is that it will work with older versions of python. locale.currency was introduced in python 2.5.


回答 9

#以类似于“ 9,348.237”的格式打印变量“总计:”

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

其中“ {:7,.3f}”是用于格式化数字的空格数,在这种情况下为百万,带有3个小数点。然后添加’.format(zum1)。zum1是tha变量,具有特定程序中所有数字之和的大数字。变量可以是您决定使用的任何东西。

#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.


回答 10

受以上代码启发: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

Inspired by the code above :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

回答 11

我来看看同一件事,发现python-money尚未真正使用它,但也许将两者混合会很好

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


回答 12

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

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'

回答 13

简单的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)

Simple python code!

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)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。