Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Python Decimal ends with a certain value

Tags:

python

decimal

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?

like image 327
NetSweet Avatar asked Dec 23 '22 02:12

NetSweet


1 Answers

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
like image 112
wim Avatar answered Jan 05 '23 00:01

wim