Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Python 2.7 and MySQLdb. I get this error on 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()

The error occurs on the line: data = data + 0.5.

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

The number is a DECIMAL(8,1). I have seen other questions with this error but not for adding. Plus, I think some people will have the same problem if they are new to Python and can't understand more advanced Python coding for similar problem questions. Could you please help me? Thanks in advance.

like image 734
Oluderi Avatar asked May 22 '15 12:05

Oluderi


People also ask

How do you convert a decimal to a float in Python?

There is two methods: float_number = float ( decimal_number ) float_number = decimal_number * 1.0.

Should I use float or decimal Python?

For most use cases, I recommend using decimals. If you initialize them with strings, you prevent subtle bugs and get the increased precision benefits. If you need to eliminate all subtle rounding issues, use the fractions module. Even though floats perform better than decimals, I recommend avoiding floats.

What is difference between float and decimal?

Float stores an approximate value and decimal stores an exact value. In summary, exact values like money should use decimal, and approximate values like scientific measurements should use float. When multiplying a non integer and dividing by that same number, decimals lose precision while floats do not.


2 Answers

There doesn't appear to be support for that operation, you will have to construct a Decimal object first and add this:

In [132]:

import decimal
​
d = decimal.Decimal(23.0)
d = d + decimal.Decimal(0.5)
d
Out[132]:
Decimal('23.5')
like image 87
EdChum Avatar answered Sep 28 '22 18:09

EdChum


This is indeed an exception for addition:

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'

You may want to do this instead:

data = data + Decimal('0.5')
like image 26
RazerM Avatar answered Sep 28 '22 18:09

RazerM