Change default float print format
>>> a = 0.1
>>> a
0.10000000000000001
>>> print a
0.1
>>> print "%0.3f" % a
0.100
>>>
From the Python docs, repr(a)
would give 17 digits (as seen by just typing a
at the interactive prompt, but str(a)
(automatically performed when you print it) rounds to 12.
Edit: Most basic hack solution... You have to use your own class though, so...yeah.
>>> class myfloat(float):
... def __str__(self):
... return "%0.3f" % self.real
>>> b = myfloat(0.1)
>>> print repr(b)
0.10000000000000001
>>> print b
0.100
>>>
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. ]]
No, because that would require modifying float.__str__()
, but you aren't allowed to monkeypatch C types. Use string interpolation or formatting instead.
You are not allowed to monkeypatch C types, like Ignacio said.
However, if you are terribly pressed in doing so and you know some C, you could go modify the Python interpreter source code yourself, then recompile it into a custom solution. Once I modified one of the standard behaviors for lists and it was only a moderate pain.
I suggest you find a better solution, such as just printing the floats with the "%0.2f"
printf notation:
for item in mylist:
print '%0.2f' % item,
or
print " ".join('%0.2f' % item for item in mylist)