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 thexas the only argument. - The
10.4fpart after the colon is the format specification. - The
fdenotes fixed-point notation. - The
10is the total width of the field being printed, lefted-padded by spaces. - The
4is the number of digits after the decimal point.
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 thexas the only argument. - The
10.4fpart after the colon is the format specification. - The
fdenotes fixed-point notation. - The
10is the total width of the field being printed, lefted-padded by spaces. - The
4is 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
General way to print floats without the .0 part
Do you normally use string.format() or percentage (%) to format your Python strings?
Firstly, you can write e. g. {0:.2f} to specify a float with 2 decimals, see e. g. https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3
Secondly, the best formatting method is f-strings, see e. g. https://www.blog.pythonlibrary.org/2018/03/13/python-3-an-intro-to-f-strings/
More on reddit.comHELP - Have a pandas dataframe of floats but want to format the # of decimal places
Don't change the dataframe. Change the presentation of the values when you print or display the data. There's no reason to truncate floats in your actual data, and you can't pad a float with zeros, you can only pad a string.
More on reddit.com