I was surprised to find that as a result of calculations, unnecessary zeros after a comma could form in a Decimal variable, for example:

>>> from decimal import Decimal >>> t = Decimal('0.001') >>> t Decimal('0.001') >>> t*100 Decimal('0.100') 

These zeros will then be on a print, in a file or in the data sent to the server, which he may not like. Why do these zeros remain? There is no sense in them, and it is unlikely that someone will ever need them. How best to remove them? Offhand comes to mind:

 from decimal import Decimal t1 = Decimal('0.1000') t2 = Decimal('1.000') print(t1, t2) def func(x): x = str(x) while x[-1] == '0': x = x[:-1] return Decimal(x) print(func(t1), func(t2)) 

But this may not be the best option, and perhaps there is already a built-in solution to this problem, which I am not aware of.

    1 answer 1

     >>> t Decimal('0.100') >>> t.normalize() Decimal('0.1') 

    There may be several reasons to keep these zeros, for example, you are working with a currency or in another area where you need to carefully specify the accuracy of measurements. Here is a good overview of the reasons (eng): http://speleotrove.com/decimal/decifaq1.html#tzeros