How do I format a floating number to a fixed width with the following requirements:
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
This question is related to
python
string
numbers
number-formatting
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:
format()
" – in this case the x
as the only argument.10.4f
part after the colon is the format specification.f
denotes fixed-point notation.10
is the total width of the field being printed, lefted-padded by spaces.4
is the number of digits after the decimal point.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
You can also left pad with zeros. For example if you want number
to have 9 characters length, left padded with zeros use:
print('{:09.3f}'.format(number))
Thus, if number = 4.656
, the output is: 00004.656
For your example the output will look like this:
numbers = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000]
for x in numbers:
print('{:010.4f}'.format(x))
prints:
00023.2300
00000.1233
00001.0000
00004.2230
09887.2000
One example where this may be useful is when you want to properly list filenames in alphabetical order. I noticed in some linux systems, the number is: 1,10,11,..2,20,21,...
Thus if you want to enforce the necessary numeric order in filenames, you need to left pad with the appropriate number of zeros.
In Python 3.
GPA = 2.5
print(" %6.1f " % GPA)
6.1f
means after the dots 1 digits show if you print 2 digits after the dots you should only %6.2f
such that %6.3f
3 digits print after the point.
I needed something similar for arrays. That helped me
some_array_rounded=np.around(some_array, 5)
This will print 76.66
:
print("Number: ", f"{76.663254: .2f}")
In python3 the following works:
>>> v=10.4
>>> print('% 6.2f' % v)
10.40
>>> print('% 12.1f' % v)
10.4
>>> print('%012.1f' % v)
0000000010.4
See Python 3.x format string syntax:
IDLE 3.5.1
numbers = ['23.23', '.1233', '1', '4.223', '9887.2']
for x in numbers:
print('{0: >#016.4f}'. format(float(x)))
23.2300
0.1233
1.0000
4.2230
9887.2000
Source: Stackoverflow.com