Formatted Integer

madDOGim 2 Tallied Votes 721 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))

Dani AI

Generated

A shorter, safer approach is to use Python’s built‑in formatting; it handles signs and grouping and is less error‑prone than hand‑rolled loops. If you want simple, robust behavior (and are happy to treat the input as an integer), this is enough:

s = input().strip()
try:
    n = int(s)
except ValueError:
    print("Invalid integer")
else:
    print(f"{n:,}")

If you need to preserve exact digit text (leading zeros) or validate the string before grouping, a small string-based routine is clearer and easier to reason about than index arithmetic:

def comma_format(s):
    s = s.strip()
    if not s:
        return ''
    sign = ''
    if s[0] in '+-':
        sign, s = s[0], s[1:]
    if not s.isdigit():
        raise ValueError("not an integer string")
    parts = []
    while s:
        parts.append(s[-3:])
        s = s[:-3]
    return sign + ','.join(reversed(parts))

print(comma_format(input()))

Common pitfalls to watch for in manual implementations: using membership (if x in '-') instead of startswith or checking the first character; using / (float division) instead of // for integer division in Python 3; comparing characters to None; and building groups left-to-right instead of grouping from the right (which causes off‑by‑one commas). Test with edge cases: negative numbers, exactly 3k digits, fewer than three digits, leading zeros, empty input and non‑digit input.

Good starting work, — and thanks to for pointing to further reading. ’s C++ question is a separate thread, but the same ideas (parse sign, validate digits, group from the right) apply if you rewrite the logic in C++.

pritaeas 2,276 Most Valuable Poster 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.