Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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!

like image 654
Prometheus Avatar asked Apr 19 '13 13:04

Prometheus


People also ask

How do I fix unsupported operand type s?

The Python "TypeError: unsupported operand type(s) for /: 'str' and 'int'" occurs when we try to use the division / operator with a string and a number. To solve the error, convert the string to an int or a float , e.g. int(my_str) / my_num .

How do you convert a decimal to a float in Python?

There is two methods: float_number = float ( decimal_number ) float_number = decimal_number * 1.0.

What does unsupported operand type S for -: NoneType and float mean?

The Python "TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'" occurs when we use the division / operator with a None value. To solve the error, figure out where the variable got assigned a None value and correct the assignment. Here is an example of how the error occurs. main.py. Copied!

What is the difference between float and decimal in Python?

Float is a single precision (32 bit) floating point data type and decimal is a 128-bit floating point data type. Floating point data type represent number values with fractional parts.


2 Answers

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.

like image 117
aldeb Avatar answered Oct 02 '22 16:10

aldeb


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.

like image 44
jymbob Avatar answered Oct 02 '22 17:10

jymbob