[英]How to multiply a floating point number and a decimal in Django?
我正在使用 django 2.0 和 Python 3.6.4
我的模型中有两个字段,称为total
和tax_total
,它们都是十进制字段。
total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
tax_total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
我想在函数中将其乘以 1.15 后计算该值。
def pre_save_cart_receiver(sender, instance, *args, **kwargs):
new_tax_total = instance.total * Decimal(1.15)
instance.tax_total = format(new_tax_total, '.2f')
pre_save.connect(pre_save_cart_receiver, sender=Cart)
它给了我错误:*不支持的操作数类型:'float'和'Decimal'
当我想添加两位小数时,我会这样做:
new_total = math.fsum([cart_total, shipping_total])
new_total_formatted = format(new_total, '.2f')
math
有类似的东西吗?
试试这个
new_tax_total = float(instance.total) * 1.15
如果您需要舍入结果,请使用round()
new_tax_total = round(float(instance.total) * 1.15,2)
其中2
是舍入整数
对于初学者和无关紧要的人,除非您想要在称为“税”的东西上获得不必要的精确度,否则我会将您的税放在一个字符串中。
from decimal import Decimal
Decimal(3.16)
=> Decimal('3.160000000000000142108547152020037174224853515625')
Decimal('3.16')
=> Decimal('3.16')
Decimal('3.16') * Decimal(2)
=> Decimal('6.32')
Decimal(3.16) * Decimal(2)
=> Decimal('6.320000000000000284217094304')
Decimal(3.16) * Decimal(2.5434)
=> Decimal('8.037144000000000693745505487')
Decimal('3.16') * Decimal('2.5434')
=> Decimal('8.037144')
至于为什么它认为你有一个来自DecimalField
的浮点数,我不知道。 所以这充其量只是部分答案,抱歉。
有点晚了,但如果有人正在寻找解决方案,我使用了这个,在 custom_tags.py 中添加了一个方法
def multiply_unversal(item1, item2):
return float(item1) * float(item2)
然后在视图中我调用 {{ data.est_number_of_shares | 内逗号}}。 注意这里的 intcomma 是为千位添加逗号分隔符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.