Can we perform calculations between Decimal objects and other values?


#1

Question

In the context of this exercise, can we perform calculations between Decimal objects and other values?

Answer

Yes, you can treat the Decimal object instances similar to a number, and apply it in operations with other numeric types, except for float values, which will cause an error.

Example

from decimal import Decimal

# With an integer.
print(Decimal("10.5") + 3) # 13.5

# With a float.
# This will give an error
print(Decimal("10.5") + 3.0)

# Instead, just use the Decimal object for float values.
print(Decimal("10.5") + Decimal("3.0")) # 13.5