Python
Floating Point
String Formatting
Fixed Width
Programming Tutorial

How to format a floating number to fixed width in Python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Fixed-width numeric formatting is essential when generating aligned reports, machine-readable text files, or audit logs. In Python, you can control width, precision, sign, and padding with format specifiers. The key is choosing a specifier that matches both display requirements and downstream parsing requirements.

Core Formatting Rules with f-Strings

A standard floating-point format specifier follows the pattern width.precision plus optional alignment and fill. For example, 10.2f means a total width of ten characters with two digits after the decimal point.

python
1def show(values):
2    for v in values:
3        print(f"|{v:10.2f}|")
4
5nums = [3.1, 123.456, -8.0, 0.004]
6show(nums)

This produces aligned columns because each rendered value has the same total width. If the value does not fit, Python expands beyond width rather than truncating. Width is a minimum, not a hard cap.

Use explicit sign controls when needed:

  • + always shows sign.
  • space reserves one sign position for positive numbers.
  • default shows minus only for negative values.
python
values = [12.4, -12.4, 0.0]
for v in values:
    print(f"default={v:8.2f} plus={v:+8.2f} space={v: 8.2f}")

Alignment, Padding, and Zero Fill

For tables, alignment matters as much as precision. Right alignment is standard for numeric columns. Left alignment is rare for numbers but common when mixing strings and values.

python
1rows = [
2    ("cpu", 7.349),
3    ("memory", 93.2),
4    ("disk", 1.005),
5]
6
7for name, metric in rows:
8    print(f"{name:<10}{metric:>10.3f}")

You can also zero-pad numbers with 0 fill, which is common in fixed-width export formats.

python
v = 42.5
print(f"|{v:010.2f}|")   # Example output like 0000042.50
print(f"|{-v:010.2f}|")  # Minus sign is preserved

Be careful with zero padding when humans read the output. It is useful for machines, but can reduce readability in dashboards.

Decimal for Financial Accuracy

Binary floating-point can introduce representation artifacts. For financial values, format Decimal objects after quantization to avoid unexpected rounding behavior.

python
1from decimal import Decimal, ROUND_HALF_UP
2
3amounts = [Decimal("12.345"), Decimal("7.5"), Decimal("100")]
4for a in amounts:
5    q = a.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
6    print(f"|{q:>10}|")

This pattern provides predictable rounding policies, which is critical for invoicing and compliance-heavy domains.

Dynamic Width and Precision in Reusable Helpers

In real systems, width and precision often come from configuration. Build helper functions so formatting rules are centralized and testable.

python
1def fixed_float(value, width=10, precision=2):
2    spec = f">{width}.{precision}f"
3    return format(value, spec)
4
5print(fixed_float(3.14159, width=12, precision=4))
6print(fixed_float(-99.5, width=8, precision=1))

A helper like this avoids repeated literal specifiers throughout the codebase and makes style changes easier.

Integration Pattern for Report Generation

In production reporting jobs, formatting decisions should be centralized in one module. Define per-column metadata with width and precision, then render rows through a single formatting function. This avoids drift where different scripts print the same metric differently. It also makes localization work easier because decimal separator and grouping policy can be swapped in one place. When output is consumed by fixed-width parsers, include tests that assert exact line length for representative records. Add test cases for negative values, zero, extremely large numbers, and very small fractions. These scenarios often expose alignment bugs that basic happy-path samples miss. Standardizing numeric formatting as an explicit contract improves interoperability and reduces downstream parsing failures.

python
1SCHEMA = {
2    "cpu": (8, 2),
3    "memory": (8, 1),
4    "latency": (10, 3),
5}
6
7def render(metrics):
8    parts = []
9    for key, value in metrics.items():
10        width, prec = SCHEMA[key]
11        parts.append(format(value, f">{width}.{prec}f"))
12    return " ".join(parts)
13
14print(render({"cpu": 7.2, "memory": 93.45, "latency": 12.0049}))

Common Pitfalls

  • Expecting width to truncate oversized numbers. Python expands output if value is longer than width.
  • Using float for money and then blaming format output for rounding surprises.
  • Forgetting sign handling, which can break alignment when negatives appear.
  • Hardcoding format strings in many places instead of centralizing rules.

Summary

  • Use format specifiers to control width, precision, and alignment.
  • Treat width as a minimum display width.
  • Prefer Decimal for financial values.
  • Use reusable helpers for configurable formatting.
  • Test with negative and large values to validate alignment.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.