1

I'm storing price as decimal(8,2) in mysql and I need to compare equality with a float in python.

Say I have 4.28 in database and select returns price = (Decimal(4.28),). I convert it to python decimal by decimal.Decimal(price[0]), but decimal.Decimal(price[0]) == 4.28 returns false.

Is there a way to compare equality directly other than comparing the difference with a small number, i.e. decimal.Decimal(price[0]) - decimal.Decimal(4.28) < 0.01

Thanks

2
  • price[0] is already decimal. Why are you trying to convert it to decimal again like decimal.Decimal(price[0])? Because decimal.Decimal(decimal.Decimal(4.28)) returned Decimal('4.28000000000000024868995751603506505489349365234375') in my laptop. Commented May 6, 2016 at 2:47
  • @ozgur price[0] is a value return from database (using mysqldb) which is not Python decimal, it literally Decimal(4.28) Commented May 6, 2016 at 2:53

2 Answers 2

5

No, there are no other way to compare float representations of numbers for equality, but there are ways to make it practical:

decimal.Decimal(price[0]) - decimal.Decimal(4.28) < 0.01

should really be:

abs(decimal.Decimal(price[0]) - decimal.Decimal(4.28)) < 0.01

You can abstract the comparison:

def almost_equal(a, b, epsilon=1e-5):
    """returns true is the absolute value of the difference between a & b 
    is less than epsilon i/e a & b are almost equal, False otherwise
    """
    return abs(a - b) < epsilon
Sign up to request clarification or add additional context in comments.

1 Comment

good pick for the abs() part. I'm only going to use it once, so probably no need to make a method for that.
1

You need to convert what you're comparing to to a decimal:

decimal.Decimal('4.28') == decimal.Decimal(price[0])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.