2

I know the problems with converting decimals to floats and vice versa. At the moment, I have a program that runs nearly always using the decimal module, but when I try to add any decimal.Decimal data type into my database it throws the error:

sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

Here is the code:

db = sqlite3.connect('test.db')
c = db.cursor()

c.execute('CREATE TABLE IF NOT EXISTS test1 (decimal REAL)')

a = Decimal(2.14) - Decimal(1.55)

c.execute("INSERT INTO test1(decimal) VALUES(?)",(a,))
db.commit()

but if I change Decimal to float it will work.

  1. will this affect the accuracy of the answers (I'm pretty sure it does)?

  2. is there a better way of doing this than to convert to float in order to store in database? If I can't store it directly in Decimal type, than I will need to be able to convert it back to Decimal after pulling it from my database.

    1. Why doesn't the "DECIMAL" data type work for this? what am I missing here?
  • One option would be to store the *string representation* of the decimal in the database, as you're correct that converting to and from float will mean loss of precision. – jonrsharpe Sep 09 '17 at 10:00
  • Thank you, let me give this a shot now. I appreciate your time – user8582502 Sep 09 '17 at 10:04
  • Simple and elegant, Idk what I didn't think of that. I guess I felt like it would've been improper, now that I know its normal to do this it makes it much more simple. Thank you Jon, I appreciate your time! Have a great day. – user8582502 Sep 09 '17 at 10:19

0 Answers0