【发布时间】:2014-02-08 02:38:45
【问题描述】:
首先,我尝试过这篇文章(以及其他):Currency formatting in Python。它对我的变量没有影响。我最好的猜测是因为我使用的是 Python 3,而那是 Python 2 的代码。(除非我忽略了某些东西,因为我是 Python 新手)。
我想将浮点数(例如 1234.5)转换为字符串,例如“$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 2.7 和 3.3。
-
如您的回答中所述,似乎不起作用
-
您的代码还有其他问题。你能发布更多的上下文吗?
-
我发布了更新版本。有什么想法吗?
-
啊,你需要给'${:,.2f}'.format(money)赋值。例如尝试money = '${:,.2f}'.format(money),然后打印出money。
标签: python python-3.x floating-point string-formatting currency