Course contentsShow
← Python
Lesson 54 of 1,0601. Foundations and EnvironmentFree lesson

Formatting Numeric Precision and Data Alignment

Learners will be able to control the decimal precision of floats and align text within fixed-width fields for professional data presentation.

In this lesson, you will learn how to make your program’s output look professional by controlling how many decimal places appear and how text is organized into neat, aligned columns.

Controlling Decimal Precision

When working with floating-point numbers, Python often displays many decimal places, which can look messy. With f-strings, you can limit the precision by adding a colon :, a period ., the number of digits you want, and the letter f (for fixed-point) inside the curly braces.

price = 19.99876
print(f"The price is {price:.2f}") 
# Output: The price is 20.00

By using :.2f, you tell Python to round the number to exactly two decimal places, making it perfect for currency or clean data reports.

Aligning Data in Fields

To create clean, table-like reports, you need to align text into fixed-width fields. You can do this by adding a colon : followed by a character to specify alignment and a number representing the total width of the space.

  • < aligns text to the left.
  • > aligns text to the right.
  • ^ centers the text.

If you specify a width of 10, Python creates a container 10 characters wide and positions your data inside it:

name = "Alice"
score = 95

# Left align name in 10 spaces, right align score in 5 spaces
print(f"{name:<10} | {score:>5}")
# Output: Alice      |    95

In this example, "Alice" occupies 10 characters of space (with spaces filling the rest), and "95" occupies 5. This ensures that even if your data varies in length, your columns will remain perfectly vertical when printed line-by-line.

Combining these techniques allows you to transform raw, unformatted numbers and strings into readable, polished information. Whether you are building a simple budget tracker or a terminal dashboard, these tools are essential for presenting your results clearly.

Key Takeaway: Use :.nf to restrict floating-point decimal precision and specify width markers like < or > inside f-string braces to create perfectly aligned, professional-looking columns.