将django FloatField限制为2个小数位 [英] Restrict django FloatField to 2 decimal places

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

问题描述

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



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

解决方案

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

从Django文档:


如果与数字整数参数一起使用,则floatformat会将数字四舍五入到许多小数位。

例如,如果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:

If used with a numeric integer argument, floatformat rounds a number to that many decimal places.

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆