NetSweet
NetSweet

Reputation: 68

Check if Python Decimal ends with a certain value

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?

Upvotes: 5

Views: 655

Answers (4)

GeeTransit
GeeTransit

Reputation: 1468

You can take advantage of the modulus operator like this:

(The modulus operator here strips the integer value. 32.48%1 turns into 0.48. The absolute value function makes it positive. abs(-32.48) will turn into 32.48. Thanks @wim.)

>>> num = float('1.4300')       # changes input into float (removes trailing 0s automatically)
>>> round(abs(num)%1, 2) == .43 # checks if it ends with .43 with 2 decimal points
True

Upvotes: 2

wim
wim

Reputation: 362716

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

Upvotes: 7

Endyd
Endyd

Reputation: 1279

You could strip your string of zeros

>>> num = Decimal('1.4300')
>>> str(num).strip('0').endswith('.43')
True

Upvotes: 0

Dan
Dan

Reputation: 537

You can convert to a string then strip off the trailing 0s before checking as follows.

num = Decimal('1.4300')
print(str(num).rstrip('0').endswith('.43'))
#Prints True

Upvotes: 2

Related Questions