Easy pretty printing of floats?
Solution 1
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.
Solution 2
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.
Solution 3
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]
Solution 4
You can do:
a = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print ["%0.2f" % i for i in a]
Solution 5
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
Related videos on Youtube
static_rtti
Creator of autojump, the fastest way to move around your filesystem from the command line.
Updated on July 08, 2022Comments
-
static_rtti almost 2 years
I have a list of floats. If I simply
print
it, it shows up like this:[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
I could use
print "%.2f"
, which would require afor
loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)>>> import print_options >>> print_options.set_float_precision(2) >>> print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08]
-
sasdev over 14 yearsA generator expression would be even better: ", ".join("%.2f" % f for f in list_o_numbers)
-
Jed Smith over 14 years@efotinis Haven't added those to my repertoire yet, but you're right -- that's pretty sexy.
-
Jed Smith over 14 yearsWhile for loops aren't ugly, this usage isn't terribly Pythonic.
-
u0b34a0f6ae over 14 years-1 terrible hack. Join formatted pieces of strings, not other way around please
-
Sakie over 14 yearsso kaizer.se, are you proposing " ".join(["%.2f" % x for x in yourlist]) . I have having to do this kind of construction in python.
-
static_rtti over 14 yearsI would have thought there was a simpler solution, but your answer is clearly the best, since you're about the only one to actually answer my question.
-
Jed Smith over 14 yearsHe's the only one to actually answer your -edited- question. Not disparaging the answerer, but you can't clarify a question and then slight the rest of the answerers based on the information we were working with.
-
u0b34a0f6ae over 14 yearsyes, I propose
" ".join("%.2f" % x for x in yourlist)
since parting format string and interpolation values is much worse than using an ugly Python idiom. -
static_rtti over 14 yearsMy original question did mention that I considered a for loop was not a good solution (for me a list comprehension is the same, but I agree that wasn't clear). I'll try being clearer next time.
-
Stephan202 over 14 years@Jed: Please read the FAQ, section "Other people can edit my stuff?!": stackoverflow.com/faq. Not every edit is a good one, but this one was a genuine improvement. Perhaps you can list both techniques in your answer, and add a note about the difference?
-
Matt Boehm over 14 yearsPython 3.1 will print the shortest decimal representation that maps to that float value. For example: >>>a, b = float(1.1), float(1.1000000000000001) >>>a 1.1000000000000001 >>>b 1.1000000000000001 >>>print(a,b) 1.1 1.1
-
Robert T. McGibbon almost 11 years[f(n) for n in x] is much more pythonic than map(f, x).
-
ToolmakerSteve over 10 yearsNOTE: In Python 2.7, for this example, the results of the "repr" line and the "str" line are identical.
-
Emile over 8 yearsThis will print ['9.00', '0.05', '0.03', '0.01', '0.06', '0.08'] - with quote marks, which you usually don't want (I prefer to have a valid list of floats printed)
-
lhk almost 8 yearsThis seems dangerous to me. You add reference semantics to the floating type. This could have strange side-effects
-
zondo over 7 yearsI'm not necessarily in favor of subclassing float, but I don't think type checking is a valid argument. When checking types,
isinstance
should be used, not equality oftype()
. When it is done correctly, a subclass of float will still be counted as a float. -
Steinarr over 7 yearsThis was the one I used but I added
.replace("'", "")
to get rid of those commas.str(["{0:0.2f}".format(i) for i in a]).replace("'", "")
-
jdhao over 6 yearsThis will produce a list of string. In the printed output, every element has
''
around it. For example, fora=[0.2222, 0.3333]
, it will produce['0.22', '0.33']
. -
Neb almost 6 yearsTo remove the apex and the commas, you should use
' '.join([{0:0.2f}".format(i) for i in a])
-
Fl.pf. about 4 yearsDon't know why this isn't higher. A solution that doesn't rely on third party libraries!
-
jjz almost 4 yearsthis is a great answer
-
Joonho Park almost 4 yearsIt is curiosity. Why is tuple working while list fails? Without "tuple", it makes error. Why?
-
Vincent Alex over 3 yearsi wouldnt use heavy package