We all know the rounding issues in Python -- that it's based on float point arithmetic, which is convenient for computers but does not always match practical, human understanding. There's plenty of questions on this on StackOverflow, though most revolve around preserving tiny decimal places, which is different than what I need below.
The solution to these rounding issues is to use the decimal
module. Yet, I must be doing something very wrong. Please, consider this, in Octave/Matlab:
>> round(2.5)
ans = 3
>> round(3.5)
ans = 4
The above are the correct results (valid in finance, applied physics, medicine, etc). We know that the same will fail in Python:
>>> round(2.5)
2
>>> round(3.5)
4
No suprise here. But when I use decimal
, I still don't receive the correct answer, and here I must be doing something wrong. Starting from the example in https://docs.python.org/3/library/decimal.html:
>>> from decimal import *
>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
Straightforward, right? But then:
>>> Decimal('3.225').quantize(TWOPLACES)
Decimal('3.22') # Wrong result. Correct would be 3.23
>>> Decimal('3.235').quantize(TWOPLACES)
Decimal('3.24') # Correct result.
So, what can I do to have the correct (as in "real world", "human-based") answer, in a fast, efficient, pythonic manner, and use the result in further computations?
EDIT: I'm using Python 3.7.3.