'How to reduce scale in python decimal value

I have a Decimal value as Decimal('3.10E-7'). How to convert it to Decimal('3.1E-7)?

I have some function (which I don't have control over) which is returning me the first value. And I am trying to write the returned value using fastavro with precision as 20 and scale as 8. For this particular value I am getting the error

ValueError: Scale provided in schema does not match the decimal

as the scale is 9.

>>> Decimal('3.10E-7').as_tuple()
DecimalTuple(sign=0, digits=(3, 1, 0), exponent=-9)
>>> Decimal('3.1E-7').as_tuple()
DecimalTuple(sign=0, digits=(3, 1), exponent=-8)

How do we convert Decimal('3.10E-7') to Decimal('3.1E-7)?



Solution 1:[1]

Decimal.normalize seems to do what you are asking for:

Normalize the number by stripping the rightmost trailing zeros [...]

Calling Decimal('3.10E-7').normalize() returns Decimal('3.1E-7').

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mkrieger1