Django中的全局十进制舍入选项 [英] Global decimal rounding options in Django
问题描述
默认情况下,十进制数会非常意外地四舍五入,为了使其正常工作,需要使用 ROUND_HALF_UP
选项。
Decimal numbers are by default rounded very unexpectedly, in order to make it work normally, it is needed to use ROUND_HALF_UP
option.
>>> from decimal import *
>>> Decimal("2.5").quantize(Decimal(1))
Decimal('2')
>>> getcontext().rounding = ROUND_HALF_UP
>>> Decimal("2.5").quantize(Decimal(1))
Decimal('3')
>>> Decimal("2.4").quantize(Decimal(1))
Decimal('2')
我的问题是-我必须在Django应用程序的哪里设置舍入选项,以便它在项目中全局运行?全局地说,我的意思是模板(floatformat模板标记),视图,模型十进制字段等。
My question is - where in the Django application I have to set rounding option, so that it would work globally in the project? By saying globally I mean templates (floatformat template tag), views, model decimal field and so on.
推荐答案
小数位数不与Django有关,它们是标准python库的一部分。 getcontext
函数返回当前线程的上下文,因此,如果您不做任何时髦的事情,每个请求都将在一个线程中执行。这基本上意味着在 settings.py
文件中设置该选项就足够了。
Decimal doesn't have anything to do with Django, they are part of the standard python library. The getcontext
function returns the context of the current thread, so if you're not doing anything funky, every request will be executed in one thread. That basically mean that setting the option in the settings.py
file should be enough.
这篇关于Django中的全局十进制舍入选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!