Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't "getcontext().prec = 2" actually setting it so the use of Decimal() goes to two decimal places?

Tags:

python

decimal

I am writing a program that deals with monetary values, as such I want it to output to two decimal places using decimal, unfortunately, this isn't working and it is outputting much longer numbers.

I've looked around online but so far it doesn't look like there are any answers for this specific issue, in case it was something happening in the rest of the program I ran a test piece of code using it just on a basic number and the same result occurred so it isn't the rest of my code. test below.

from decimal import *
getcontext().prec = 2
test = Decimal(5.859)
print(test)

I expected this to print the output of 5.86 or in the worst case at least 5.85 if it didn't round in the desired direction.

Instead, it printed.

5.8589999999999999857891452847979962825775146484375

the same output as though getcontext().prec = 2 was never used

Please be aware moderately new to python so please don't just assume I'll know exactly what you mean if you throw random code at me without an explanation.

like image 482
Jay Avatar asked Oct 18 '25 11:10

Jay


1 Answers

As per this documentation, Context precision and rounding only come into play during arithmetic operations. So, in order to achieve your goal, you can do something like this:

from decimal import *
getcontext().prec = 3
test = Decimal('5.859')/Decimal('1')
print(test)

output:

Decimal('5.86')
like image 68
Anubhav Singh Avatar answered Oct 21 '25 02:10

Anubhav Singh