本文介绍了将django FloatField限制为2个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来将Django中的FloatField限制在小数点后两位,任何人都可以知道如何在不使用DecimalField的情况下完成这一任务。



decimal_places = 2 但这只是给我浮动字段内的迁移错误,所以我想这个方法只能在DecimalFields内工作。

解决方案

如果您只关心 FloatField ,您可以使用模板过滤器 floatformat

从Django文档:

例如,如果value = 34.23234 ,然后在你的模板中:

  {{value | floatformat:2}}#outputs 34.23 


I am looking for a way to limit the FloatField in Django to 2 decimal places has anyone got a clue of how this could be done without having to use a DecimalField.

I tried decimal_places=2but this was just giving me a migration error within the float field so i am thinking this method must only work within DecimalFields.

If you are only concerned with how your FloatField appears in forms, you can use the template filter floatformat.

From the Django Docs:

For example, if value = 34.23234, then in your template:

{{ value|floatformat:2 }}  # outputs 34.23

这篇关于将django FloatField限制为2个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 09:18