Explain Codes LogoExplain Codes Logo

How to format a floating number to fixed width in Python

python
formatting
precision
alignment
Nikita BarsukovbyNikita Barsukov·Sep 28, 2024
TLDR

A swift solution to format floats in Python, using 10-character-wide space with 2 decimal places precision, can be achieved either using the built-in format() function or the f-string.

format() function:

formatted = "{:10.2f}".format(123.456) # Output: ' 123.46', why did number take a nap? It’s two-tired!

f-string:

formatted = f"{123.456:10.2f}" # Output: ' 123.46', When life gives you round-off errors, make decimal-aide!

The result is an alignment of the number to the right in a 10 spaces field, rounded off to 2 decimal places.

Using precision and right alignment

While precising the number of decimal places, it's also possible to align the float value to the right by stipulating the overall field width.

number = 3.1415 formatted = f"{number:10.4f}" # ' 3.1415', When python aligns things right, life feels π-ful!

Alignment of decimals for comparison

For a list of numbers, using consistent formatting aligns all the decimal points neatly in columns, simplifying comparison.

numbers = [123.456, 78.9, 3.14] formatted = [f"{num:10.2f}" for num in numbers] # [' 123.46', ' 78.90', ' 3.14'], When three numbers walked into a bar…

The art of leading zeros

Handle numbers less than one or those needing precise string ordering/visual alignment by padding them with leading zeros.

formatted = f"{0.123456:09.6f}" # '00.123456', it’s size 0 that still thinks it's a size 6!

Achieving dynamic width and precision

Variables come handy when you need a flexible control over field widths and precision for more complex formatting scenarios.

width, precision = 10, 4 formatted = f"{number:{width}.{precision}f}" # ' 3.1415', flexible as my yoga teacher!

Adapting to fixed width

Accommodating excess decimal digits while maintaining the fixed width can be tricky. A good solution is to truncate the number.

formatted = f"{123.456789:10.4}" # Compute so fast you'll forget the extra decimals!

Ensuring numerical order with the right padding

When working with sampling data or sorting files, proper padding with leading zeros ensures numeric order.

Padding Filenames with Zeros: Filenames can now carry meaningful sequential numbers without causing confusion:

for i in range(1, 11): filename = f"file_{i:03d}.txt" # file_001.txt, file_010.txt ; An effective file naming session!

Maintaining Numeric Order in Lists: Sorting lists with leading zeros surely keeps the natural numerical order.

numbers = [3.14, 200.5, 42.22] formatted = sorted(f"{num:07.2f}" for num in numbers) # Sorting: Reducing complex to simple, just like a zen master.