A quick and dirty way is to redefine Decimal
itself at the beginning of your main module:
from decimal import Decimal
Decimal.__repr__ = lambda self: "{0:.2f}".format(self)
This would apply to all decimals, including any created in external modules.
Another way would be to make your own Decimal
subclass, but defining new types for simple conveniences like this is a bad habit to get into, I think: If any external function returns an object of the base type, then you need to convert it to a new object of your type which is needlessly inefficient. Also, Decimal
uses slots and is meant to be an immutable type, so any subclass would need to take this into account to preserve efficiency.
A better way would be to define your own function for displaying it the way you want. This way you limit the reformatting to specifically when you want to use it. However this function would need to re-implement the recursive list output algorithm. Fortunately, there is the repr library which greatly simplifies this. This allows you to define custom repr
implementations per type, with built-in support for recursive objects like lists and dictionaries:
from decimal import Decimal
from repr import Repr
class CustomRepr(Repr):
def repr_Decimal(self, obj, level):
return "{0:.2f}".format(obj)
cr = CustomRepr()
data = {"money": [Decimal("42")]}
print cr.repr(data)
Output:
{'money': [42.00]}