Formatted Integer

madDOGim 2 Tallied Votes 709 Views Share

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
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))
pritaeas 2,194 ¯\_(ツ)_/¯ Moderator Featured Poster

You might want to have a look at this:

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

commented: Awesome +0
Koos_1 -4 Newbie Poster

Hy guys, how can I read comma delimited list from text file into an array in c++

pritaeas commented: This should be a new question, not a reply on a question with a different topic and language. -4
Be a part of the DaniWeb community

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