1

十进制数字默认四舍五入非常意外,为了使其正常工作,需要使用ROUND_HALF_UP选项。

>>> 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 模板标签)、视图、模型十进制字段等等。

4

4 回答 4

3

在 1.9.5 中工作(基于 @ark 的评论):

在 myapp/apps.py

from __future__ import unicode_literals
import decimal
from django.apps import AppConfig


class MyAppConfig(AppConfig):

    name = 'myapp'

    def ready(self):
        # Set precision
        decimal.getcontext().prec = 9
        decimal.getcontext().rounding = decimal.ROUND_HALF_DOWN

在 settings.py

INSTALLED_APPS = list(INSTALLED_APPS)
INSTALLED_APPS.append('myapp.apps.MyAppConfig')
于 2016-05-07T19:56:39.730 回答
1

Decimal 与 Django 没有任何关系,它们是标准 python 库的一部分。该getcontext函数返回当前线程的上下文,所以如果你没有做任何时髦的事情,每个请求都将在一个线程中执行。这基本上意味着在settings.py文件中设置选项就足够了。

于 2013-08-06T19:09:09.460 回答
0

实际上它不像 Viktor 建议的那样工作(尽管在 django 1.5 中)。

我的解决方案是创建和使用这样的中间件:

# -*- coding: utf-8 -*-

import decimal
from django.conf import settings


class DecimalPrecisionMiddleware(object):
    def process_request(self, request):
        decimal_context = decimal.getcontext()
        decimal_context.prec = settings.DECIMAL_PRECISION # say: 4

然后在 settings.py 中:

MIDDLEWARE_CLASSES = (
    'pathto.middleware.DecimalPrecisionMiddleware',
    # etc..
)
于 2013-12-23T18:21:42.410 回答
0

对于 django 项目可以设置 decimal.DefaultContext ( py3 , py2 )。

此上下文在多线程环境中最有用。

这是我的代码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

在 1.10 中工作。根据我对这个问题的回答。

于 2018-04-27T06:47:56.077 回答