問題描述
首先,我嘗試過這篇文章(以及其他):Python 中的貨幣格式.它對我的變量沒有影響.我最好的猜測是因?yàn)槲沂褂玫氖?Python 3,而那是 Python 2 的代碼.(除非我忽略了某些東西,因?yàn)槲沂?Python 新手).
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).
我想將浮點(diǎn)數(shù)(例如 1234.5)轉(zhuǎn)換為字符串,例如$1,234.50".我該怎么做呢?
為了以防萬一,這是我編譯的代碼,但不影響我的變量:
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)
同樣失敗:
money = float(1234.5)
print(money) #output is 1234.5
'${:,.2f}'.format(money)
print(money) #output is 1234.5
推薦答案
在 Python 3.x 和 2.7 中,您可以簡單地這樣做:
In Python 3.x and 2.7, you can simply do this:
>>> '${:,.2f}'.format(1234.5)
'$1,234.50'
:,
添加逗號作為千位分隔符,.2f
將字符串限制為小數(shù)點(diǎn)后兩位(或添加足夠的零以達(dá)到小數(shù)點(diǎn)后兩位,視情況而定)在最后.
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.
這篇關(guān)于將浮點(diǎn)數(shù)轉(zhuǎn)換為美元和美分的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!