unsupported operand type(s) for *: 'float' and 'Decimal'

PythonDjango

Python Problem Overview


I'm just playing around learning classes functions etc, So I decided to create a simple function what should give me tax amount.

this is my code so far.

class VAT_calculator:
    """
     A set of methods for VAT calculations.
    """

    def __init__(self, amount=None):
        self.amount = amount
        self.VAT = decimal.Decimal('0.095')

    def initialize(self):
        self.amount = 0

    def total_with_VAT(self):
        """
        Returns amount with VAT added.
        """
        if not self.amount:
            msg = u"Cannot add VAT if no amount is passed!'"
            raise ValidationError(msg)

        return (self.amount * self.VAT).quantize(self.amount, rounding=decimal.ROUND_UP)

My issue is I'm getting the following error:

>unsupported operand type(s) for : 'float' and 'Decimal'*

I don't see why this should not work!

Python Solutions


Solution 1 - Python

It seems like self.VAT is of decimal.Decimal type and self.amount is a float, thing that you can't do.

Try decimal.Decimal(self.amount) * self.VAT instead.

Solution 2 - Python

Your issue is, as the error says, that you're trying to multiply a Decimal by a float

The simplest solution is to rewrite any reference to amount declaring it as a Decimal object:

self.amount = decimal.Decimal(float(amount))

and in initialize:

self.amount = decimal.Decimal('0.0')

Another option would be to declare Decimals in your final line:

return (decimal.Decimal(float(self.amount)) * self.VAT).quantize(decimal.Decimal(float(self.amount)), rounding=decimal.ROUND_UP)

...but that seems messier.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrometheusView Question on Stackoverflow
Solution 1 - PythonaldebView Answer on Stackoverflow
Solution 2 - PythonjymbobView Answer on Stackoverflow