It looks to me like there are two parts to this question - one, determining the correct number of digits and two, quantizing the values to that number of digits.
To do the first, I would get the current exponent using the as_tuple()
method. Unless I'm overlooking something simpler.
>>> import decimal
>>> d = decimal.Decimal("1.678")
>>> d.as_tuple().exponent
-3
>>> d2 = decimal.Decimal("1.6")
>>> d2.as_tuple().exponent
-1
So from that you can compute the desired exponent:
MAX_EXPONENT = -2
MIN_EXPONENT = -5
def desired_exponent(d):
current_exponent = d.as_tuple().exponent
return min(MAX_EXPONENT, max(MIN_EXPONENT, current_exponent))
The second is answered by the accepted answer on the marked duplicate - use the quantize() method. You'll need to construct a Decimal
value with the desired exponent you can provide as the argument to quantize()
. There are multiple ways to do that, but two simple ones are exponentiating decimal.Decimal("10")
or using the tuple
constructor for decimal.Decimal()
.
>>> quant_arg = decimal.Decimal("10") ** -2
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')
Or:
>>> quant_arg = decimal.Decimal((0, (), -2))
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')
I used -2 as a literal there, you'd want to use the calculated value of desired_exponent
.
There are multiple ways to organize this code, I think the parts that are not obvious are a) accessing the current exponent of a decimal value and b) some of the ways of constructing an arg for quantize()
. And this is all assuming you need the actual decimal objects, and aren't just outputting them - if this is a question just about output formatting re-quantizing is probably overkill.