Easy pretty printing of floats?
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]
You can do:
a = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print ["%0.2f" % i for i in a]
It's an old question but I'd add something potentially useful:
I know you wrote your example in raw Python lists, but if you decide to use numpy
arrays instead (which would be perfectly legit in your example, because you seem to be dealing with arrays of numbers), there is (almost exactly) this command you said you made up:
import numpy as np
np.set_printoptions(precision=2)
Or even better in your case if you still want to see all decimals of really precise numbers, but get rid of trailing zeros for example, use the formatting string %g
:
np.set_printoptions(formatter={"float_kind": lambda x: "%g" % x})
For just printing once and not changing global behavior, use np.array2string
with the same arguments as above.
Note that you can also multiply a string like "%.2f" (example: "%.2f "*10).
>>> print "%.2f "*len(yourlist) % tuple(yourlist)
2.00 33.00 4.42 0.31