Python Add Comma Into Number String

前端 未结 9 1033
陌清茗
陌清茗 2020-11-29 02:37

Using Python v2, 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          


        
相关标签:
9条回答
  • 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()!")
    
    0 讨论(0)
  • 2020-11-29 03:07

    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
    
    0 讨论(0)
  • 2020-11-29 03:10

    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.

    0 讨论(0)
  • 2020-11-29 03:15

    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)) 
    
    0 讨论(0)
  • 2020-11-29 03:22

    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
    
    0 讨论(0)
  • 2020-11-29 03:24

    I feel comfortable using like this in python:

    input_value=float(input())
    print("{:,}".format(input_value))
    
    0 讨论(0)
提交回复
热议问题