From the answer, https://stackoverflow.com/a/33948596/47078, you could do something like the following. I'm not sure, though, if what you want is possible without additional code: namely to have a Decimal that preserves precision automatically.
>>> import decimal
>>> f = decimal.Context(prec=4).create_decimal('0.1230')
>>> f
Decimal('0.1230')
>>> decimal.Context(prec=4).create_decimal(f * 100)
Decimal('12.30')
You may want to write your own class or helper methods to make it look nicer.
>>> Decimal4 = decimal.Context(prec=4).create_decimal
>>> Decimal4('0.1230')
Decimal('0.1230')
>>> Decimal4(Decimal4('0.1230') * 100)
Decimal('12.30')
Looks like (from decimal.Context.create_decimal) you can also do it this way:
# This is copied verbatim from the Python documentation
>>> getcontext().prec = 3
>>> Decimal('3.4445') + Decimal('1.0023')
Decimal('4.45')
>>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
Perhaps you could create a method to replace Decimal() that creates the Decimal object, and updates the global precision if the current precision is less than the current.
>>> def make_decimal(value):
... number = decimal.Decimal(value)
... prec = len(number.as_tuple().digits)
... if prec < decimal.getcontext().prec:
... decimal.getcontext().prec = prec
... return number
...
>>> make_decimal('0.1230')
Decimal('0.1230')
>>> make_decimal('0.1230') * 100
Decimal('12.30')
You would then want a reset_decimal_precision
method or an optional parameter to make_decimal
to do the same so you could start new calculations. The downside is that it limits you to only one global precision at a time. I think the best solution might be to subclass Decimal() and make it keep track of precision.