As no one has added it, it should be noted that going forward from Python 2.6+ the recommended way to do string formating is with format, to get ready for Python 3+.
print ["{0:0.2f}".format(i) for i in a]
The new string formating syntax is not hard to use, and yet is quite powerfull.
I though that may be pprint could have something, but I haven't found anything.
As no one has added it, it should be noted that going forward from Python 2.6+ the recommended way to do string formating is with format, to get ready for Python 3+.
print ["{0:0.2f}".format(i) for i in a]
The new string formating syntax is not hard to use, and yet is quite powerfull.
I though that may be pprint could have something, but I haven't found anything.
A more permanent solution is to subclass float:
>>> class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
>>> x
[1.290192, 3.0002, 22.119199999999999, 3.4110999999999998]
>>> x = map(prettyfloat, x)
>>> x
[1.29, 3.00, 22.12, 3.41]
>>> y = x[2]
>>> y
22.12
The problem with subclassing float is that it breaks code that's explicitly looking for a variable's type. But so far as I can tell, that's the only problem with it. And a simple x = map(float, x) undoes the conversion to prettyfloat.
Tragically, you can't just monkey-patch float.__repr__, because float's immutable.
If you don't want to subclass float, but don't mind defining a function, map(f, x) is a lot more concise than [f(n) for n in x]
How can I control the number of decimals when printing a float?
General way to print floats without the .0 part
Trying to format a list of floats with f-strings
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.comVideos
I want to control how many digits will be printed after the decimal point when printing a float.
The function will take a, b and p as inputs, divide a/b, and I need it to show p number of decimals.
For example, if a/b = 123.456789, then:
If p = 2, then output 123.46 If p = 3, then output 123.457 If p = 10, then output 123.4567890000
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'