Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to format a floating number to fixed width in Python?
In Python, formatting a floating point number to a fixed width can be done using methods like Python's f-strings and the flexible format() method.
Float Formatting Methods
The two built-in float formatting methods are as follows ?
-
f-strings: Convenient way to set decimal places, spacing and separators.
-
str.format(): This method allows formatting types inside the placeholders to control how the values are displayed.
Using f-strings
We can format a floating-point number to a fixed width by using Python's f-strings. In the format specification {number:10.2f}, the 10 specifies the total width and .2f specifies 2 decimal places ?
Example
number = 123.4568
formatted = f"{number:10.2f}"
print(formatted)
The output of the above code is ?
123.46
Using str.format() Method
The str.format() method is versatile for formatting strings in Python. Using this method, we can also control padding and alignment ?
Example
number = 123.4568
formatted = "{:10.2f}".format(number)
print(formatted)
The output of the above code is ?
123.46
Padding and Alignment Options
We can control padding and alignment using the str.format() method with these alignment specifiers ?
-
Right Align (>): Right-aligns the number within the specified width (default behavior).
-
Left Align (<): Left-aligns the number within the specified width.
-
Center Align (^): Centers the number with spaces on both sides.
-
Zero Padding (0): Pads the number with zeros on the left side instead of spaces.
Example
number = 838.65
# Right align with spaces (default)
right_align = "{:>10}".format(number)
print('Right Align:', right_align)
# Left align with spaces
left_align = "{:<10}".format(number)
print('Left Align: ', left_align)
# Center align with spaces
center_align = "{:^10}".format(number)
print('Center Align:', center_align)
# Zero padding
zero_padding = "{:010.2f}".format(number)
print('Zero Padding:', zero_padding)
The output of the above code is ?
Right Align: 838.65 Left Align: 838.65 Center Align: 838.65 Zero Padding: 0000838.65
Format Specification Summary
| Format | Description | Example |
|---|---|---|
{:10.2f} |
Width 10, 2 decimal places | Right-aligned with spaces |
{:<10.2f} |
Left-aligned, width 10 | Left-aligned with spaces |
{:^10.2f} |
Center-aligned, width 10 | Centered with spaces |
{:010.2f} |
Zero-padded, width 10 | Padded with leading zeros |
Conclusion
Use f-strings for modern, readable formatting with f"{number:10.2f}" syntax. The str.format() method provides the same functionality with more explicit control over alignment and padding options.
