简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM