Python * 不支持的操作数类型:“float”和“Decimal”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16105485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
unsupported operand type(s) for *: 'float' and 'Decimal'
提问by Prometheus
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'**
* 不支持的操作数类型:'float' 和 'Decimal'**
I don't see why this should not work!
我不明白为什么这不起作用!
采纳答案by aldeb
It seems like self.VATis of decimal.Decimaltype and self.amountis a float, thing that you can't do.
它似乎self.VAT是一种decimal.Decimal类型,self.amount是一种float你不能做的事情。
Try decimal.Decimal(self.amount) * self.VATinstead.
试试吧decimal.Decimal(self.amount) * self.VAT。
回答by jymbob
Your issue is, as the error says, that you're trying to multiply a Decimalby a float
您的问题是,正如错误所说,您试图将 a 乘以Decimalafloat
The simplest solution is to rewrite any reference to amountdeclaring it as a Decimal object:
最简单的解决方案是重写任何引用以将其amount声明为 Decimal 对象:
self.amount = decimal.Decimal(float(amount))
self.amount = decimal.Decimal(float(amount))
and in initialize:
并在initialize:
self.amount = decimal.Decimal('0.0')
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)
return (decimal.Decimal(float(self.amount)) * self.VAT).quantize(decimal.Decimal(float(self.amount)), rounding=decimal.ROUND_UP)
...but that seems messier.
...但这似乎更混乱。

