将浮动转换为美元和美分

问题描述 投票:40回答:5

首先,我试过这篇文章(其中包括):Currency formatting in Python。它对我的变量没有影响。我最好的猜测是因为我使用的是Python 3,而且是Python 2的代码。(除非我忽略了一些东西,因为我是Python新手)。

我想将一个浮点数(如1234.5)转换为String,例如“$ 1,234.50”。我该怎么做呢?

为了以防万一,这里是我编译的代码,但不影响我的变量:

money = float(1234.5)
locale.setlocale(locale.LC_ALL, '')
locale.currency(money, grouping=True)

也不成功:

money = float(1234.5)
print(money) #output is 1234.5
'${:,.2f}'.format(money)
print(money) #output is 1234.5
python python-3.x floating-point string-formatting currency
5个回答
109
投票

在Python 3.x和2.7中,您可以简单地执行此操作:

>>> '${:,.2f}'.format(1234.5)
'$1,234.50'

:,将逗号添加为千位分隔符,.2f将字符串限制为两位小数(或者在末尾添加足够的零以达到2位小数,视情况而定)。


11
投票

建立@ JustinBarber的例子并注意@ eric.frederich的评论,如果你想格式化负值,如-$1,000.00而不是$-1,000.00,并且不想使用locale

def as_currency(amount):
    if amount >= 0:
        return '${:,.2f}'.format(amount)
    else:
        return '-${:,.2f}'.format(-amount)

9
投票

在python 3中,您可以使用:

import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
locale.currency( 1234.50, grouping = True )

产量

'$1,234.50'

0
投票

就个人而言,我更喜欢这个(这被认为是一种不同的方式来编写当前选择的“最佳答案”):

money = float(1234.5)
print('$' + format(money, ',.2f'))

或者,如果你真的不喜欢“添加”多个字符串来组合它们,你可以这样做:

money = float(1234.5)
print('${0}'.format(format(money, ',.2f')))

我只是觉得这两种风格都更容易阅读。 :-)

(当然,你仍然可以使用If-Else处理负值,正如Eric所说的那样)


-2
投票

你之前这么说:

`mony = float(1234.5)
print(money)      #output is 1234.5
'${:,.2f}'.format(money)
print(money)

不起作用....你是否完全按照这种方式编码?这应该工作(看到一点点差异):

money = float(1234.5)      #next you used format without printing, nor affecting value of "money"
amountAsFormattedString = '${:,.2f}'.format(money)
print( amountAsFormattedString )
© www.soinside.com 2019 - 2024. All rights reserved.