Search code examples
pythonfloating-pointdecimalrounding-error

Python Decimals


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

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.