Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change default float print format

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?

like image 636
AkiRoss Avatar asked Jul 16 '10 12:07

AkiRoss


2 Answers

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)
like image 52
Donald Miner Avatar answered Nov 12 '22 04:11

Donald Miner


>>> 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
>>>
like image 21
Nick T Avatar answered Nov 12 '22 04:11

Nick T