Formatted Integer

madDOGim

I solved a problem some day ago. In that problem you had to format an integer. I found it hard to solve. So here I am sharing my problem with you.

Problem:
Read an integer variable and print it in which the digits are separated into groups of three by commas.

Input: 12345678
Output: 12,345,678

Any changes of my code will be appreciated.

Dani commented: Thanks for sharing :) +34
444 Views
About the Author
def format(text, l, formatted):
    """format the text if it is devided by 3 """
    if l <= 3:
        formatted += text
    elif l%3 == 0 and l/3 != 1:
        comma = l / 3 - 1
        comma_counter = 0
        pos = 0
        while pos < len(text) and text[pos] != None:
            if pos != 0 and (pos+1)%3 == 0:
                formatted += text[pos]
                comma_counter += 1
                if comma_counter <= comma:
                    formatted += ','
            else:
                formatted += text[pos]
            pos += 1
    return formatted


n = input()

if n in '-':
    formatted = '-'
    text = n.replace('-', '')
    l = len(text)
    if l <= 3:
        formatted += text
        print(formatted)
    elif l%3 == 0:
        print(format(text, l, formatted))
    else:
        fc = l%3
        if fc == 1:
            formatted += text[0] + ','
            text = text[1:]
            l = len(text)
            print(format(text, l, formatted))
        else:
            formatted += text[:2] + ','
            text = text[2:]
            l = len(text)
            print(format(text, l, formatted))
else:
    formatted = ''
    text = n
    l = len(text)
    if l <= 3:
        formatted += text
        print(formatted)
    elif l%3 == 0:
        print(format(text, l, formatted))
    else:
        fc = l%3
        if fc == 1:
            formatted += text[0] + ','
            text = text[1:]
            l = len(text)
            print(format(text, l, formatted))
        else:
            formatted += text[:2] + ','
            text = text[2:]
            l = len(text)
            print(format(text, l, formatted))

You might want to have a look at this:

https://www.peterbe.com/plog/format-thousands-in-python

commented: Awesome +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.