Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy pretty printing of floats?

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 a for 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] 
like image 482
static_rtti Avatar asked Oct 14 '09 15:10

static_rtti


People also ask

How do you print only a float in Python?

format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do I print a formatted float in Python?

Output. To format the float value up to two decimal places, use the %. 2f.

What is Python float precision?

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.


1 Answers

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.

like image 96
Esteban Küber Avatar answered Oct 18 '22 20:10

Esteban Küber