Home > Back-end >  TypeError: unsupported operand type(s) for /: 'float' and 'decimal.Decimal'
TypeError: unsupported operand type(s) for /: 'float' and 'decimal.Decimal'

Time:01-03

Let us consider my views.py

def ajax_add_other_order_item(request,id):
   client = request.user.client

   def _convert(from_currency, to_currency, price):
       custom_rate_obj = client.custom_rates.filter(currency=to_currency).first()
       if custom_rate_obj is None or custom_rate_obj.exchange_rate in (0, None):
          custom_rate_obj = ExchangeRates.objects.latest('created')
       return custom_rate_obj.convert(from_currency, to_currency, price)
   if request.method == 'POST':
      unit = request.POST.get('u_price') or 0
      if supplier.currency:
         currency = supplier.currency
      else:
         currency = request.POST.get('currency', 'GBP')
      purchase_price = _convert(currency, 'GBP', float(unit))
      try:
          exchange_price = float(unit)/purchase_price
      except ZeroDivisionError:
          exchange_price = 0

     trade_price = math.ceil(_convert(currency, client.currency, float(unit)) * val)

Here i am getting error TypeError: unsupported operand type(s) for /: 'float' and 'decimal.Decimal' Please help to solve this issue

CodePudding user response:

You can not divide a float with a Decimal, since a decimal has a fixed number of digits, whereas a float uses the IEEE-754 encoding and has not a fixed number of digits.

You can convert the number to a Decimal, and then do the division accordingly:

from decimal import Decimal

try:
    exchange_price = Decimal(unit)/purchase_price
except ZeroDivisionError:
    exchange_price = Decimal(0)

CodePudding user response:

from decimal import Decimal

...

exchange_price = Decimal(unit)/purchase_price
  • Related