Can we perform calculations between Decimal objects and other values?

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
6 Likes

There must be a way to cast a float() to another type. The closest I got was with this below. I used 0.0 to illustrate the point and to make sure the answer was still 0.89 which it was.

two_decimal_points = Decimal("0.2") + Decimal("0.69") + Decimal(str((float(0.0))))

1 Like

In your second code. Where we are adding a flot number with a Decimal(float), here why we are getting error?

>>> from decimal import Decimal
>>> dir(Decimal)

That will give us a list of all the methods of the Decimal class. Ignore the dunder methods as they are generally used internally.

In the list we spot, from_float. Let’s check with HELP to see its usage and syntax…

>>> help(Decimal.from_float)
Help on built-in function from_float:

from_float(f, /) method of builtins.type instance
    Class method that converts a float to a decimal number, exactly.
    Since 0.1 is not exactly representable in binary floating point,
    Decimal.from_float(0.1) is not the same as Decimal('0.1').
    
        >>> Decimal.from_float(0.1)
        Decimal('0.1000000000000000055511151231257827021181583404541015625')
        >>> Decimal.from_float(float('nan'))
        Decimal('NaN')
        >>> Decimal.from_float(float('inf'))
        Decimal('Infinity')
        >>> Decimal.from_float(float('-inf'))
        Decimal('-Infinity')

>>> 

This doesn’t really answer any questions as much as peer under the hood. The more we study this module, the more practical use we would hope to discover. It will take a lot of tinkering, one suspects owing to the massive amount of abstraction.

3 Likes

what this code is doing i didn’t understand a bit. i thought float is a number but here float is a word. what and how this code is operating float please explain it.

More I try to explain it, more it confuses. This is a module that will take extensive study, more than I have invested to now. Perhaps look for the practical applications of the Decimal module and it will become easier to implement with purpose, rather than novelty. Sorry I could not be of more help.

4 Likes

great advice, thanks mtf