Is there any way to do computations with fixed number of digits after decimal point?

Viewed 38

For some application I need to my computations using 3 digits of precision after decimal. I found the following method:

getcontext().prec = 100

THREE_PLACES = Decimal('0.001')

x = Decimal('2.41').quantize(THREE_PLACES)

y = (x * x).quantize(THREE_PLACES)

but This makes the code very ugly because I need to write quantize(THREE_PLACES) for all my operations which are actually a lot. And also the numbers I am getting with may be very big so that getcontext().prec = 100 may not work for all of them. Any better alternates to this one ? I also found the solution using f string's but that makes the code even uglier.

Edit: I have to explain that getcontext().prec sets the number of significat digits not digits after decimal and because I may have big enough numbers I set it to a big number. See here.

0 Answers
Related