89

I have a value running through my program that puts out a number rounded to 2 decimal places at the end, like this:

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

Is there a way to insert a comma value every 3 digits left of the decimal point?

e.g. 10000.00 becomes 10,000.00 or 1000000.00 becomes 1,000,000.00.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
The Woo
  • 17,809
  • 26
  • 57
  • 71

11 Answers11

148

In Python 2.7 and 3.x, you can use the format syntax :,

>>> total_amount = 10000
>>> print("{:,}".format(total_amount))
10,000
>>> print("Total cost is: ${:,.2f}".format(total_amount))
Total cost is: $10,000.00

This is documented in PEP 378 -- Format Specifier for Thousands Separator and has an example in the Official Docs "Using the comma as a thousands separator"

ti7
  • 16,375
  • 6
  • 40
  • 68
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
36

if you are using Python 3 or above, here is an easier way to insert a comma:

First way

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

or another way

value = -12345672
print ('{:,}'.format(value)) 
Community
  • 1
  • 1
cooldeal
  • 351
  • 3
  • 2
18

You could use locale.currency if TotalAmount represents money. It works on Python <2.7 too:

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

Note: it doesn't work with the C locale so you should set some other locale before calling it.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
16

another way very short is

value = -122212123.12
print(f"{value:,}")
T H
  • 423
  • 4
  • 7
8
'{:20,.2f}'.format(TotalAmount)
Peter Kelly
  • 14,253
  • 6
  • 54
  • 63
7

This is not particularly elegant but should work too :

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]
ThR37
  • 3,965
  • 6
  • 35
  • 42
5

A function that works in python2.7+ or 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()!")
dnaman7
  • 51
  • 1
  • 3
4

Latest versions of python use f-strings. So you can do this:

print("Total cost: {total_amount:,}

As long as total_amount is a not a string. Otherwise you'd need to cast it to a number type first like so:

print("Total cost: {Decimal(total_amount):,}
EnterPassword
  • 580
  • 1
  • 6
  • 22
1

The above answers are so much nicer than the code I was using in my (not-homework) project:

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
QBFreak
  • 11
  • 2
  • "The above answers are so much nicer than the code I was using" - If existing answers are better, then there is no need to post a lower-quality answer. Additionally, this post already has an accepted answer. – avojak Jul 14 '17 at 15:10
  • 1
    At the time I was thinking it would be useful to future googlers as it didn't have the minimum Python version that some of the other answers did. Upon another review of the answers I see there already is one. – QBFreak Jul 16 '17 at 12:56
  • +1. I like this. It gives a good breakdown and gives coders the ability to port this logic easily to other languages. – Jake Ireland Apr 30 '21 at 06:49
0

Started learning Python about 5 hours ago, but I think I came up with something for integers (sorry, couldn't figure out floats). I'm in high school, so big chance the code could be way more efficient; I just made something from scratch that made sense to me. If anyone has any ideas on how to improve with ample explanation of how it works, let me know!

# 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
Drake Johnson
  • 640
  • 3
  • 19
0

I feel comfortable using like this in python:

input_value=float(input())
print("{:,}".format(input_value))
FahimFBA
  • 27
  • 6
  • 1
    Note this question was answered 9 years ago, with your answer being discussed already within the top 2 answers. – Ranoiaetep Nov 12 '20 at 06:58