2011-03-03 66 views
23

使用Python V2,我要通過我的程序 是推出在最後四捨五入至小數點後2位的一些運行值:Python中添加逗號進入號串

這樣的:

print ("Total cost is: ${:0.2f}".format(TotalAmount)) 

有沒有辦法在小數點左邊每隔3位插入一個逗號值?

即:10000.00成爲10,000.00或1000000.00成爲1,000,000.00

感謝您的幫助。

+7

胡:四個問題在不到一個小時的時間內就同一主題。你正在完成你的功課位。布拉沃。 – joaquin

回答

50

在Python 2.7或以上,你可以使用

print ("Total cost is: ${:,.2f}".format(TotalAmount)) 

這在PEP 378記錄。

(從你的代碼,我不能告訴你正在使用的Python版本。)

+0

對不起,我正在使用v2 –

+0

但該代碼也適用於版本2。謝謝。 –

+0

這顯然是功課。並不是說我有任何問題,但是:1)。它實際上並沒有教會OP什麼。 2)。這使得SO成爲回答作業問題的天堂。 – user225312

4
'{:20,.2f}'.format(TotalAmount) 
14

你可以使用locale.currency如果TotalAmount代表錢。它適用於Python的< 2.7太:

>>> locale.setlocale(locale.LC_ALL, '') 
'en_US.utf8' 
>>> locale.currency(123456.789, symbol=False, grouping=True) 
'123,456.79' 

注意:它不與C現場工作,所以你應該在調用它之前設置一些其他的語言環境。

2

這是不是特別優雅,但應太:

a = "1000000.00" 
e = list(a.split(".")[0]) 
for i in range(len(e))[::-3][1:]: 
    e.insert(i+1,",") 
result = "".join(e)+"."+a.split(".")[1] 
+1

完美的解決方案。 – Wok

5

如果您正在使用的Python 3以上,這裏是插入一個逗號更簡單的方法:

第一種方式

value = -12345672 
print (format (value, ',d')) 

或其他方式

value = -12345672 
print ('{:,}'.format(value)) 
+0

可能的值是float,而不是整數,所以它會是'format(value,「,f」)' – mehtunguh

2

在python2.7 +或python3.1工作的功能+

def comma(num): 
    '''Add comma to every 3rd digit. Takes int or float and 
    returns string.''' 
    if type(num) == int: 
     return '{:,}'.format(num) 
    elif type(num) == float: 
     return '{:,.2f}'.format(num) # Rounds to 2 decimal places 
    else: 
     print("Need int or float as input to function comma()!") 
0

以上的答案是如此,比我用我的(非作業)項目中的代碼更好了:

def commaize(number): 
    text = str(number) 
    parts = text.split(".") 
    ret = "" 
    if len(parts) > 1: 
     ret = "." 
     ret += parts[1] # Apparently commas aren't used to the right of the decimal point 
    # The -1 offsets to len() and 0 are because len() is 1 based but text[] is 0 based 
    for i in range(len(parts[0]) - 1,-1,-1): 
     # We can't just check (i % 3) because we're counting from right to left 
     # and i is counting from left to right. We can overcome this by checking 
     # len() - i, although it needs to be adjusted for the off-by-one with a -1 
     # We also make sure we aren't at the far-right (len() - 1) so we don't end 
     # with a comma 
     if (len(parts[0]) - i - 1) % 3 == 0 and i != len(parts[0]) - 1: 
      ret = "," + ret 
     ret = parts[0][i] + ret 
    return ret 
+0

「上面的答案比我使用的代碼好得多」 - 如果現有答案更好,那麼沒有必要發佈質量較低的答案。另外,這篇文章已經有了一個被接受的答案。 – avojak

+0

當時我認爲這對未來的谷歌搜索引擎是有用的,因爲它沒有其他答案的最小Python版本。經過對答案的另一個回顧,我看到那裏已經有一個。 – QBFreak