How to set global rounding for DecimalFields in Django project?

烂漫一生 提交于 2019-12-25 17:46:49

问题


I found similar question with answers, but "setting the option in the settings.py" and "setting getcontext() in apps.py" doesn't work. Standard decimal rounding is ROUND_HALF_EVEN, but I need to set ROUND_HALF_UP.

And I repeat my question with a quote - "where in the Django application I have to set rounding option, so that it would work globally in the project?"


回答1:


For django project can work setting decimal.DefaultContext (py3, py2).

This context is most useful in multi-threaded environments.

This is my code from settings.py:

import decimal
# Set global decimal rounding to ROUND_HALF_UP (instead of ROUND_HALF_EVEN).
project_context = decimal.getcontext()
project_context.rounding = decimal.ROUND_HALF_UP
decimal.DefaultContext = project_context


来源:https://stackoverflow.com/questions/50042364/how-to-set-global-rounding-for-decimalfields-in-django-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!