Python Добавить запятую в числовую строку - PullRequest
34 голосов
/ 03 марта 2011

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

, например:

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

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

Т.е.: 10000,00 становится 10 000,00 или 1000000,00 становится 1 000 000,00

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

Ответы [ 8 ]

64 голосов
/ 03 марта 2011

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

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

Это задокументировано в PEP 378 .

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

15 голосов
/ 03 марта 2011

Вы можете использовать locale.currency, если TotalAmount представляет деньги.Он работает и на Python <2.7: </p>

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

Примечание: он не работает с языком C, поэтому вы должны установить другой язык перед вызовом.

9 голосов
/ 13 августа 2014

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

Первый путь

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

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

value = -12345672
print ('{:,}'.format(value)) 
4 голосов
/ 14 марта 2016

Функция, которая работает в 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()!")
4 голосов
/ 03 марта 2011
'{:20,.2f}'.format(TotalAmount)
2 голосов
/ 03 марта 2011

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

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]
0 голосов
/ 17 февраля 2019

Начал изучать Python около 5 часов назад, но я думаю, что придумал что-то для целых чисел (извините, не мог найти числа с плавающей запятой). Я учусь в старшей школе, поэтому большой шанс, что код станет более эффективным; Я просто сделал что-то с нуля, что имело смысл для меня. Если у кого-нибудь есть какие-либо идеи о том, как улучшить работу, и достаточно объяснений, как это работает, дайте мне знать!

# 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
0 голосов
/ 14 июля 2017

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

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...