Unsupported operand type(s) for *: float and decimal.Decimal

Wed Apr 20 20221 min read

Photo by Andres Molina

Unsupported operand type(s) for *: float and decimal.Decimal#

The Python "TypeError: unsupported operand type(s) for *: 'float' and 'decimal.Decimal'" occurs when we try to use the multiplication operator with a float and a `Decimal` object. To solve the error, convert the float to a decimal, e.g. `Decimal(my_float) * my_decimal`.

Here is an example of how the error occurs.

main.py
```Copied!```from decimal import Decimal

my_float = 3.2
my_decimal = Decimal('3.14')

# ⛔️ TypeError: unsupported operand type(s) for *: 'float' and 'decimal.Decimal'
result = my_float * my_decimal
``````

We are trying to use the division operator with a `Decimal` object and a float.

Since `Decimal` objects and floats are handled differently, we have to convert the floating-point number to a `Decimal` object.

main.py
```Copied!```from decimal import Decimal

my_float = 3.2
my_decimal = Decimal('3.14')

result = Decimal(my_float) * my_decimal

print(result)  # 👉️ 10.04800000000000055777604757
``````

We used the decimal.Decimal class to construct a new Decimal object from a value.

The value we pass to the `decimal.Decimal` class can be an integer, string, tuple, float, or another `Decimal` object.

If you call the `Decimal` class without passing a value, it returns `0`.

If you aren't sure what type a variable stores, use the built-in `type()` class.

main.py
```Copied!```from decimal import Decimal

my_float = 3.2
print(type(my_float))  # 👉️ <class 'float'>
print(isinstance(my_float, float))  # 👉️ True

my_decimal = Decimal('3.14')
print(type(my_decimal))  # 👉️ <class 'decimal.Decimal'>
print(isinstance(my_decimal, Decimal))  # 👉️ True
``````

The type class returns the type of an object.

The isinstance function returns `True` if the passed in object is an instance or a subclass of the passed in class.

Use the search field on my Home Page to filter through my more than 1,000 articles.