Подтвердить что ты не робот

Python Добавить запятую в строку номера

Используя Python v2, у меня есть значение, проходящее через мою программу который выдает число, округленное до 2 десятичных знаков в конце:

вот так:

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

Есть ли способ вставить значение запятой каждые 3 цифры слева от десятичной точки?

Т.е.: 10000.00 становится 10000,00 или 1000000.00 становится 1,000,000.00

Спасибо за любую помощь.

4b9b3361

Ответ 1

В Python 2.7 или выше вы можете использовать

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

Это описано в PEP 378.

(Из вашего кода я не могу определить, какую версию Python вы используете.)

Ответ 2

Вы можете использовать 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, поэтому перед его вызовом вы должны установить другой язык.

Ответ 3

если вы используете Python 3 или выше, это более простой способ вставить запятую:

Первый способ

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

или другим способом

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

Ответ 4

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

Ответ 5

Это не особенно элегантно, но также должно работать:

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

Функция, которая работает в 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()!")

Ответ 7

Вышеупомянутые ответы намного лучше, чем код, который я использовал в моем проекте (не домашняя работа):

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