Sometimes, we want to format a floating number to fixed width in Python.
In this article, we’ll look at how to format a floating number to fixed width in Python.
How to format a floating number to fixed width in Python?
To format a floating number to fixed width in Python, we can use the string format
method.
For instance, we write
numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]
for x in numbers:
print("{:10.4f}".format(x))
to call format
with the numbers x
in the numbers
list.
We format each number in the list to 4 decimal places with "{:10.4f}"
.
Conclusion
To format a floating number to fixed width in Python, we can use the string format
method.