1. Home
  2. Data & files

Data files · formatting

Integer to String Conversion: Digits, Padding and Bases

Eigenfield editorial team ·

An integer to string conversion turns the number 4075 into the four characters 4, 0, 7, 5. Programs need it for file names, row labels, log messages, and any place where a count has to sit inside text. The operation is simple, but a few details decide whether the output is usable: padding, sign, base, and the behavior when the input is a float that only looks like an integer. The sections below cover each one. The reverse direction is covered under ASCII to double conversion.

How the digits are produced

The standard method divides by the base and collects remainders. For 4075 in base 10:

  • 4075 = 407 × 10 + 5, so the last digit is 5.
  • 407 = 40 × 10 + 7, so the next digit is 7.
  • 40 = 4 × 10 + 0, so the next digit is 0.
  • 4 = 0 × 10 + 4, so the first digit is 4.

The remainders come out in reverse order, 5, 7, 0, 4, and the string is read backward as 4075. The loop stops when the quotient reaches zero. A special case is needed for the input 0 itself, because the loop body never runs and the result would be empty instead of the single character 0.

def int_to_str(n, base=10):
    if n == 0:
        return "0"
    digits = "0123456789abcdef"
    sign = "-" if n < 0 else ""
    n = abs(n)
    out = []
    while n > 0:
        n, r = divmod(n, base)
        out.append(digits[r])
    return sign + "".join(reversed(out))

print(int_to_str(4075))        # 4075
print(int_to_str(255, 16))     # ff

The hexadecimal check is easy by hand: 255 = 15 × 16 + 15, and 15 is the digit f, so the answer is ff. In practice the built-in formatting routines do all this, but knowing the loop helps when debugging a surprising output.

Padding and width

File names such as frame_7.dat and frame_10.dat sort in the wrong order alphabetically, because the character 1 comes before 7. Zero padding to a fixed width fixes this: 7 becomes 007 and 10 becomes 010. Choose the width from the largest value that will occur, with one spare digit if the count may grow. A format specifier like %06d, or the equivalent in the language at hand, pads 4075 to 004075.

Negative numbers need a decision about where the sign goes. Padding with zeros after the sign gives -00042, which most formatters do by default. Padding before the sign would give 000-42, which nothing can parse.

When the input is a float

The most common mistake is passing a floating-point value and expecting an integer string. Some routines round to nearest, some truncate toward zero, and some refuse. The value 2.5 becomes 2 under round-half-to-even and 3 under round-half-up, and −2.5 differs again under truncation. If the number came out of a calculation, the safer path is to round explicitly with the rule the application needs, convert the result to an integer type, and only then to text.

Very large values raise a second concern. A double represents every integer exactly only up to 2⁵³, which is 9,007,199,254,740,992. Beyond that, neighboring integers collapse into the same double, and the printed digits are the digits of the stored value, not of what the formula intended.

Checking round trips

A quick test for any converter is a round trip: convert a range of integers to text, parse the text back, and compare. Include 0, negative values, the largest value the type allows, and a few numbers that end in zeros. Any mismatch points to a padding or sign bug. Tabulated output is where this matters most; see reading spreadsheet files into a matrix for the matching input side, and quoting strings for what to do when the text is placed inside delimited fields. Shared vocabulary lives in the glossary.

Back to top