Change default float print format

Viewed 29817

I've some lists and more complex structures containing floats. When printing them, I see the floats with a lot of decimal digits, but when printing, I don't need all of them. So I would like to define a custom format (e.g. 2 or 3 decimals) when floats are printed.

I need to use floats and not Decimal. Also, I'm not allowed to truncate/round floats.

Is there a way to change the default behavior?

7 Answers

This doesn't answer the more general question of floats nested in other structures, but if you just need to print floats in lists or even array-like nested lists, consider using numpy.

e.g.,

import numpy as np
np.set_printoptions(precision=3, suppress=False)
list_ = [[1.5398, 2.456, 3.0], 
         [-8.397, 2.69, -2.0]]
print(np.array(list_))

gives

[[ 1.54   2.456  3.   ]
 [-8.397  2.69  -2.   ]]
Related