使用Python v2,我的程序中有一个值 在最后输出一个四舍五入到小数位数的数字:
像这样:print ("Total cost is: ${:0.2f}".format(TotalAmount))
有没有办法在小数点左边每3位数插入一个逗号值?
即:10000.00变为10,000.00或1000000.00变为1,000,000.00
感谢您的帮助。
答案 0 :(得分:63)
在Python 2.7或更高版本中,您可以使用
print ("Total cost is: ${:,.2f}".format(TotalAmount))
PEP 378中记录了这一点。
(从您的代码中,我无法分辨您正在使用哪个Python版本。)
答案 1 :(得分:15)
如果TotalAmount
代表金钱,您可以使用locale.currency
。它适用于Python< 2.7;
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.utf8'
>>> locale.currency(123456.789, symbol=False, grouping=True)
'123,456.79'
注意:它不适用于C
语言环境,因此您应在调用之前设置其他语言环境。
答案 2 :(得分:9)
如果您使用 Python 3 或更高版本,则可以通过以下方式轻松插入逗号:
value = -12345672
print (format (value, ',d'))
value = -12345672
print ('{:,}'.format(value))
答案 3 :(得分:4)
'{:20,.2f}'.format(TotalAmount)
答案 4 :(得分:4)
在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()!")
答案 5 :(得分: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]
答案 6 :(得分: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
答案 7 :(得分:0)
大约5个小时前开始学习Python,但是我想我想出了一些用于整数的方法(对不起,无法弄清楚浮点数)。我在上高中,所以代码很有可能会更高效。我只是从头开始做了一些对我来说有意义的事情。如果有人对如何改进有任何想法,并对其进行了充分的解释,请告诉我!
# Inserts comma separators
def place_value(num):
perm_num = num # Stores "num" to ensure it cannot be modified
lis_num = list(str(num)) # Makes "num" into a list of single-character strings since lists are easier to manipulate
if len(str(perm_num)) > 3:
index_offset = 0 # Every time a comma is added, the numbers are all shifted over one
for index in range(len(str(perm_num))): # Converts "perm_num" to string so len() can count the length, then uses that for a range
mod_index = (index + 1) % 3 # Locates every 3 index
neg_index = -1 * (index + 1 + index_offset) # Calculates the index that the comma will be inserted at
if mod_index == 0: # If "index" is evenly divisible by 3
lis_num.insert(neg_index, ",") # Adds comma place of negative index
index_offset += 1 # Every time a comma is added, the index of all items in list are increased by 1 from the back
str_num = "".join(lis_num) # Joins list back together into string
else: # If the number is less than or equal to 3 digits long, don't separate with commas
str_num = str(num)
return str_num
答案 8 :(得分:0)
在python中使用这样的代码我感到很舒服:
input_value=float(input())
print("{:,}".format(input_value))
答案 9 :(得分:-1)
最新版本的 python 使用 f-strings。所以你可以这样做:
print("Total cost: {total_amount:,}
只要 total_amount 不是字符串。否则,您需要先将其转换为数字类型,如下所示:
print("Total cost: {Decimal(total_amount):,}