Django 中的小数点四舍五入无法按预期工作?

问题描述 投票:0回答:1

我使用的是 Django 版本 3.2.16。

在 Django 中我使用下面的代码。

这里例如,收入__所有权是2500,金额字段的值是14826。因此,当将14826乘以25时,得到的值为37.715,我希望四舍五入的结果为35.72,但Django Round给出的结果为36。如何实现所需的结果?

amount_annotation = ExpressionWrapper(
    # Use Django's Round function to round the base value to 2 decimal places
    Round(
        F(amount_field) * (Cast(F('income__ownership'), FloatField()) / 10000),
        precision=2,  # Round to 2 decimal places
        output_field=FloatField()
    ) * 100,  # Multiply the rounded value by 100
    output_field=IntegerField()
)
django orm rounding
1个回答
0
投票

我建议您使用另一种方法,而是使用 python 内置

round
方法。 在这种情况下,您可以进行计算,然后获得所需的行为。

amount_annotation =  F(amount_field) * (Cast(F('income__ownership'), FloatField()) / 10000)


rounded_value = round(amount_annotation , 2)
final_amount_annotation = ExpressionWrapper(
rounded_value * 100,
output_field=IntegerField()
)

当然,你应该检查一下这段代码,因为我没有尝试过。

© www.soinside.com 2019 - 2024. All rights reserved.