1

I'm trying to create a small app for calculation of expenses. It already works with float, but I suppose that using decimals can make code more clear and simple. Just a small example to show the issue that I have:

    import decimal
    decimal.getcontext().prec = 2
    print ("{}".format(decimal.Decimal(1)/decimal.Decimal(3)))

the output is 0.33 and 2 digits is what I need.

Let's increase the first number from 1 up to 10:

    import decimal
    decimal.getcontext().prec = 2
    print ("{}".format(decimal.Decimal(10)/decimal.Decimal(3)))

the output is 3.3 and it is not that kind of representation that I need. I still would like to have two digits after delimiter: 3.33 instead of 3.3. I have tried different ways like using localcontext, but haven't succeed:

    from decimal import Context, localcontext, Decimal
    with localcontext(Context(2)):
        print((Decimal("10") / 3))

So, as I can see decimal.getcontext().prec defines the number of digits after delimiter if the variable < 1 or defines the total number of digits if the variable > 0. I'm wondering does some simple solution always keep 2 digits after delimiter exists? This case seems quite common and I believe that there should be a simple and elegant solution which was found before me.

Update: It seems that description wasn't clear enough, therefore, my question was linked to another one. Let's try to clarify :) I'm looking for a way to define data format once at the beginning and keep it after instead of using quantize() each time when I do division or multiplication operations. quantize() solves issue only for one variable and this variable shouldn't be changed after that. For instance, if I have 10 operations then I should use quantize() 10 times that doesn't seem effective and in such case, I don't see significant reasons to change code and use decimals instead of float.

Yurii
  • 11
  • 2
  • A valid question, though mathematicaly 0.2 * 0.3 adds precisions 1+1, 0.06 (precision 2). – Joop Eggen Apr 24 '20 at 11:27
  • @Mihai Chelaru thanks, it helps, but I still have to use quantize() after each division or multiplication to control the precision. I would be glad to define precision once at the beginning and don't care about it after. – Yurii Apr 24 '20 at 12:25

0 Answers0