将浮动转换为美元和美分 [英] Converting Float to Dollars and Cents
问题描述
我想将浮点数(例如1234.5)转换为一个字符串,例如$ 1,234.50。我怎么会这样做?
为了以防万一,这里是我编译的代码,但不影响我的变量:
money = float(1234.5)
locale.setlocale(locale.LC_ALL,'')
locale.currency(money ,grouping = True)
也不成功:
< pre $ $ code $ money $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b print(money)#output is 1234.5
3.x和2.7,你可以简单地做到这一点:
>>>格式(1234.5)
'$ 1,234.50'
'$ {:,。2f} :,
将一个逗号作为千位分隔符,而 .2f
将字符串限制为两位小数(或
。加上足够的零来得到2个小数位,视情况而定)
First of all, I have tried this post (among others): Currency formatting in Python. It has no affect on my variable. My best guess is that it is because I am using Python 3 and that was code for Python 2. (Unless I overlooked something, because I am new to Python).
I want to convert a float, such as 1234.5, to a String, such as "$1,234.50". How would I go about doing this?
And just in case, here is my code which compiled, but did not affect my variable:
money = float(1234.5)
locale.setlocale(locale.LC_ALL, '')
locale.currency(money, grouping=True)
Also unsuccessful:
money = float(1234.5)
print(money) #output is 1234.5
'${:,.2f}'.format(money)
print(money) #output is 1234.5
In Python 3.x and 2.7, you can simply do this:
>>> '${:,.2f}'.format(1234.5)
'$1,234.50'
The :,
adds a comma as a thousands separator, and the .2f
limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.
这篇关于将浮动转换为美元和美分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!