How to format a floating number to fixed width in Python
How do I format a floating number to a fixed width with the following requirements:
- Leading zero if n < 1
- Add trailing decimal zero(s) to fill up fixed width
- Truncate decimal digits past fixed width
- Align all decimal points
For example:
% formatter something like '{:06}'
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]
for number in numbers:
print formatter.format(number)
The output would be like
23.2300
0.1233
1.0000
4.2230
9887.2000
Solution 1:
numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]
for x in numbers:
print("{:10.4f}".format(x))
prints
23.2300
0.1233
1.0000
4.2230
9887.2000
The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:
- The empty string before the colon means "take the next provided argument to
format()
" – in this case thex
as the only argument. - The
10.4f
part after the colon is the format specification. - The
f
denotes fixed-point notation. - The
10
is the total width of the field being printed, lefted-padded by spaces. - The
4
is the number of digits after the decimal point.
Solution 2:
It has been a few years since this was answered, but as of Python 3.6 (PEP498) you could use the new f-strings
:
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]
for number in numbers:
print(f'{number:9.4f}')
Prints:
23.2300
0.1233
1.0000
4.2230
9887.2000