python - Django:n个小数字段的乘法返回具有n * 2个小数位的结果
问题描述
我正在使用 django,我有这个模型:
class CartLine(DeletableModel):
product = models.ForeignKey('Product', related_name='cart_lines', on_delete=do_nothing)
cart = models.ForeignKey('Cart', related_name='lines', on_delete=do_nothing)
quantity = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_('Quantity'))
@property
def total_sum(self):
return self.product.price * self.quantity
class Meta:
verbose_name = _('Cart Line')
verbose_name_plural = _('Cart Lines')
当我在模板中使用属性 total_sum 时{{ line.product.price }}
,它会返回结果300.0000
。即使我尝试使用过滤器标签 floatformat 就像{{ line.product.price|floatformat:2 }}
它返回相同的值一样,它也没有格式化它。
所以我去了python shell并尝试了它,它返回了相同的值:
>>> cartline.total_sum
Decimal('300.0000')
当我将属性更改为:
@property
def total_sum(self):
return self.product.price * self.quantity * self.quantity
并在控制台中对其进行了测试:
cartline.total_sum
Decimal('900.000000')
这就像连接小数位......当我进行乘法或任何其他操作时,我该如何解决这个问题或解决这个问题以将显示限制为 2 个小数位?
解决方案
schwobaseggl评论通过尝试解决了我的问题total_sum.quantize(Decimal("0.01"))
推荐阅读
- api - 来自其他 IP 地址的 GitHub API 令牌使用
- qt - Qt Creator“调试”和“运行”不同的应用程序行为,都在调试配置中,C++17
- unicode - 如何在单词边界处换行包含 ANSI 颜色代码的 Unicode 文本?
- python - 如何使用 Flask Response 返回 TXT 文件?
- python - 暂停和恢复爬网时出现意外结果
- vtk - 如何将 VTKMolecule 转换为 Polydata?
- mongodb - MongoDB AddToSet 如何防止特定字段重复?
- postgresql - “BinaryExpression”对象和“比较器”对象都没有属性“过滤器”
- ios - Flutter app size huge, how to reduce for ios
- javascript - 将鼠标坐标存储到 Firebase