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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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.

typeerror unsupported operand type for asterisk float and decimal decimal

Here is an example of how the error occurs.

main.py
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
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
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.

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.