TypeError: unsupported operand type for +: 'decimal' and 'float'

I am using Python 2.7 and MySQLdb. I get this error in this code:

Value = 5 x.execute("SELECT number from Testing where id ='%s';" % Value) data = x.fetchall() print (data) data = data[0][0] data = data + 0.5 x.execute(""" UPDATE Testing SET number = %s WHERE id = %s """, (data, Value)) conn.commit() 

Error on the line: data = data + 0.5 .

TypeError: unsupported operand type(s) for +: 'decimal' and 'float'.

The number is DECIMAL(8,1) . I saw other questions with this error, but not for adding. In addition, I think that some people will have the same problem if they are new to Python and cannot understand the more advanced Python encoding for such problematic issues. could you help me? Thanks in advance.

+6
source share
2 answers

This operation does not seem to be supported, you need to first create a Decimal object and add this:

 In [132]: import decimal​ d = decimal.Decimal(23.0) d = d + decimal.Decimal(0.5) d Out[132]: Decimal('23.5') 
+6
source

This is really an exception to add:

 from decimal import Decimal Decimal('0.1') + 0.2 

 TypeError Traceback (most recent call last) <ipython-input-3-9bb7f0cfb622> in <module>() 1 from decimal import Decimal ----> 2 Decimal('0.1') + 0.2 TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float' 

Instead, you can do this:

 data = data + Decimal('0.5') 
+1
source

Source: https://habr.com/ru/post/987740/


All Articles