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
Trying to format a list of floats with f-strings
How to say this more succinctly in python, and why? ... n = float(format(float(sys.argv[1]), '.2f'))
I'd do this using math rather than string formatting. So if you take any arbitrary number, what series of math operations would you need to remove any trailing digits?
More on reddit.comHow to think about integers, strings, and floats?
How to format floating numbers using inbuilt methods in Python?
How do I limit a float to only show 2 decimal places?
How do I display infinity or nan values properly?
Videos
roots = [sqrt(i) for i in numbers]
print(f'Roots: {roots}')So Im trying to gain control of the precision of my floats, as Im practicing list comprehension and such, this particular print doesn't work.
I really dig these new fstrings but I cant figure out where to put in the ':.3f in the code.
print(f'Roots: {[root for root in roots]}')This is as far as ive come but when i put in the formatter on root its 'invalid syntax'