I want to be able to compare Decimals in Python. For the sake of making calculations with money, clever people told me to use Decimals instead of floats, so I did. However, if I want to verify that a calculation produces the expected result, how would I go about it?

>>> a = Decimal(1./3.)
>>> a
Decimal('0.333333333333333314829616256247390992939472198486328125')
>>> b = Decimal(2./3.)
>>> b
Decimal('0.66666666666666662965923251249478198587894439697265625')
>>> a == b
False
>>> a == b - a
False
>>> a == b - Decimal(1./3.)
False

so in this example a = 1/3 and b = 2/3, so obviously b-a = 1/3 = a, however, that cannot be done with Decimals.

I guess a way to do it is to say that I expect the result to be 1/3, and in python i write this as

Decimal(1./3.).quantize(...)

and then I can compare it like this:

(b-a).quantize(...) == Decimal(1./3.).quantize(...)

So, my question is: Is there a cleaner way of doing this? How would you write tests for Decimals?

Edit
Report