I have a bunch of Decimal objects. I want to test each one to see if it ends in .43. I can do this by first converting it to a string:
>>> num = Decimal('1.43')
>>> str(num).endswith('.43')
True
But that fails if I don't know what precision the Decimal was created with.
>>> num = Decimal('1.4300')
>>> str(num).endswith('.43')
False
I could do the string conversion and check if it contains .43.
>>> num = Decimal('1.4300')
>>> '.43' in str(num)
True
But that also matches other values, which I don't want.
>>> num = Decimal('1.4321')
>>> '.43' in str(num)
True
How can I check if the decimal ends in .43, with any number of trailing zeroes?
It will be best to use mathematical reasoning here, avoiding the float domain (inaccurate) and the string domain (unnecessary).  If you subtract 0.43 from a number ending in .43, you should be left with an integer, and you can check that using modulo operator %:
>>> point43 = Decimal("0.43") 
>>> num = Decimal('1.43') 
>>> (abs(num) - point43) % 1 == 0 
True
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With