Evo*_*lor 47 python floating-point currency string-formatting python-3.x
首先,我尝试过这篇文章(其中包括):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)
Run Code Online (Sandbox Code Playgroud)
也不成功:
money = float(1234.5)
print(money) #output is 1234.5
'${:,.2f}'.format(money)
print(money) #output is 1234.5
Run Code Online (Sandbox Code Playgroud)
πόδ*_*κύς 120
在Python 3.x和2.7中,您可以简单地执行此操作:
>>> '${:,.2f}'.format(1234.5)
'$1,234.50'
Run Code Online (Sandbox Code Playgroud)
在:,增加了一个逗号作为千位分隔符,以及.2f限制串到小数点后两位末(或添加足够的零去小数点后2位,视情况而定).
Ale*_*lec 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)
Run Code Online (Sandbox Code Playgroud)
小智 11
在python 3中,您可以使用:
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
locale.currency( 1234.50, grouping = True )
Run Code Online (Sandbox Code Playgroud)
产量
'$1,234.50'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84826 次 |
| 最近记录: |