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

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

问题描述

我正在寻找一种将 Django 中的 FloatField 限制为 2 个小数位的方法,有没有人知道如何在不使用 DecimalField 的情况下完成此操作.

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.

我尝试了 decimal_places=2 但这只是给我一个浮点字段内的迁移错误,所以我认为这个方法只能在 DecimalFields 中工作.

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.

推荐答案

如果您只关心 FloatField 在表单中的显示方式,您可以使用模板过滤器 floatformat.

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

来自 Django 文档:

From the Django Docs:

如果与数字整数参数一起使用,floatformat 会将一个数字四舍五入到那么多小数位.

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

例如,如果 value = 34.23234,则在您的模板中:

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

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

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

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