2011-03-03 68 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