Django 舍入小数的最佳实践:前端还是后端?
我有一个相当广泛的 Django 站点,用于处理需要显示 2 位小数的货币金额,但由于对这些金额执行数学运算,因此在幕后使用 4 位小数。某些页面通过 AJAX 调用(作为 JSON)获取这些金额,而其他页面则通过标准视图获取这些金额 =>模板变量传递。我的模型使用 models.DecimalField(max_digits=10,decimal_places=4, default=Decimal('0'))
现在网站已经足够大了,我需要找到一种一致的方法来处理这个小数四舍五入,但无论我用哪种方式,都显得很尴尬。这是我能想到的两种方法,但每种方法似乎都不太理想。
前端:视图保留小数点不变,保留 4 位。模板使用
floatformat:2
过滤器,JS 函数使用.toFixed(2)
来转换传入的 JSON 数据。问题:需要在模板代码和 JS 代码中处理多处舍入。后端:视图将所有小数四舍五入到 2 位,并将它们作为字符串传递给模板。同样,对传入 AJAX 调用的响应将所有小数序列化为 2 位。问题:视图现在处理格式而不是模板,并且特殊情况不能在模板中采用不同的格式。
是否有一种“正确的,Djangonic”的方式来处理小数舍入?
I have a fairly extensive Django site that deals with currency amounts that need to be displayed with 2 decimal places, but since there are mathematical operations performed on these amounts, behind the scenes, 4 place decimals are used. Some pages get these amounts via AJAX calls (as JSON) and other pages get them via the standard view => template variable passing. My models use models.DecimalField(max_digits=10, decimal_places=4, default=Decimal('0'))
The site is large enough now that I need to figure out a consistent way to handle this decimal rounding, but no matter which way I do it, it seems awkward. Here are the two ways I can think of, but each seems less than ideal.
Frontend: views leave the decimals unchanged, with 4 places. Templates use the
floatformat:2
filter and JS functions use.toFixed(2)
for the conversion of incoming JSON data. Problem: need to handle the rounding in many places in template code and JS code.Backend: views round all decimals to 2 places and pass them as strings to the templates. Likewise, responses to incoming AJAX calls serialize all decimals to 2 places. Problem: views are now handling formatting instead of templates and special cases cannot be formatted differently in the template.
Is there a "proper, Djangonic" way of handling Decimal rounding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
考虑到这纯粹是一个演示问题,我的直觉是将其保留在模板中。也就是说,模板应该尽可能简单,并且您可能不想将小数位计数硬编码为整个模板中的幻数。
我可能会做类似以下的事情:
这样您就可以将所有表示逻辑保留在模板级别,但仍然保持 DRY 原则。它仍然意味着对模板和 JavaScript 进行大量编辑,但我真的想不出任何更干净的方法来做到这一点,而不进入真正的 hacky 领域。
Considering that this is purely a presentation issue, my instinct would be keep it in the templates. That said, the templates should be as dumb as possible, and you probably don't want to hard code your decimal place counts as magic numbers all over your templates.
I would probably do something like the following:
That way your keep all your presentation logic at the template level, but you still maintain DRY principles. It still means lots of edits to your templates and JavaScript, but I can't really think of any cleaner way to do it without getting into really hacky territory.