简体   繁体   English

如何在 Django 中将浮点数和小数相乘?

[英]How to multiply a floating point number and a decimal in Django?

I am using django 2.0 and Python 3.6.4我正在使用 django 2.0 和 Python 3.6.4

I have two fields in my model called total and tax_total both of them are decimal fields.我的模型中有两个字段,称为totaltax_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)

I want to calculate the value after multiplying it with 1.15 in a function.我想在函数中将其乘以 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)

It's giving me errors: unsupported operand type(s) for *: 'float' and 'Decimal'它给了我错误:*不支持的操作数类型:'float'和'Decimal'

When I want to add two decimals, I do:当我想添加两位小数时,我会这样做:

    new_total           = math.fsum([cart_total,  shipping_total])
    new_total_formatted = format(new_total, '.2f')

Is there anything like that from math ? math有类似的东西吗?

try this试试这个

new_tax_total      = float(instance.total) * 1.15

if you need to round the result, use round()如果您需要舍入结果,请使用round()
new_tax_total = round(float(instance.total) * 1.15,2) where 2 is the rounding interger new_tax_total = round(float(instance.total) * 1.15,2)其中2是舍入整数

For starters and unrelated unless you want uneeded precision on something called "tax" I would put your tax in a string.对于初学者和无关紧要的人,除非您想要在称为“税”的东西上获得不必要的精确度,否则我会将您的税放在一个字符串中。

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')

As for why it thinks you have a float from a DecimalField , that is unknown to me.至于为什么它认为你有一个来自DecimalField的浮点数,我不知道。 So this is a partial answer at best, sorry.所以这充其量只是部分答案,抱歉。

A bit late, but in case someone is looking for a solution, i used this one, adding a method in the custom_tags.py有点晚了,但如果有人正在寻找解决方案,我使用了这个,在 custom_tags.py 中添加了一个方法

def multiply_unversal(item1, item2):
    return float(item1) * float(item2)

Then in the view I call {{ data.est_number_of_shares |然后在视图中我调用 {{ data.est_number_of_shares | intcomma }}.内逗号}}。 Note the intcomma here is add comma separator for thousands.注意这里的 intcomma 是为千位添加逗号分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM