Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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').

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading