Sometimes, we want to format a floating number to a fixed width in Python.
In this article, we’ll look at how to format a floating number to a fixed width in Python.
How to format a floating number to a fixed width in Python?
To format a floating number to a fixed width in Python, we can use a special formatting code with the string’s format
method.
For instance, we write:
numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]
for x in numbers:
print("{:10.3f}".format(x))
to format all the numbers in numbers
to strings with 3 decimal places.
The {:10.3f}
formatting code rounds each number to 3 decimal places.
Therefore, we see:
23.230
0.123
1.000
4.223
9887.200
printed.
Conclusion
To format a floating number to a fixed width in Python, we can use a special formatting code with the string’s format
method.