Question

I expect 0.5 to round up to 1. Can anybody explain why it rounds down to 0 instead?

>>> from decimal import *
>>> getcontext().prec = 0
>>> +Decimal(0.5)
Decimal('0')
Was it helpful?

Solution

You asked for zero significant digits of precision. If you don't allow any digits at all to be stored, all numbers will be zero.

Note that the precision is the number of significant decimal digits, that is, not counting leading zeros. 0.5 has a single significant digit, 1.5 has two. Also note that Decimal uses banker's rounding.

OTHER TIPS

you're setting the precision to 0, try setting it to 1 or 2 instead.

I'm not sure what the use case is here, but why not just do:

round(0.5)

I would just convert to an int if you want an integer.

 int(Decimal(0.5))

You could also make sure you have the right rounding setting.

 getcontext().prec = 0
 getcontext().rounding = ROUND_HALF_UP

In your:

getcontext.prec()=0

line, you are asking for 0 decimal places - all decimals will return 0 this way. Try:

getcontext.prec()=1

Or another number to set the amount of decimal places.

Good luck.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top