Global decimal rounding options in Django

后端 未结 4 743
生来不讨喜
生来不讨喜 2021-01-24 11:14

Decimal numbers are by default rounded very unexpectedly, in order to make it work normally, it is needed to use ROUND_HALF_UP option.

>>>          


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-24 11:39

    Actually it doesn't work like Viktor suggested (although in django 1.5).

    My solution is create and using a middleware like this:

    # -*- 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
    

    and then in settings.py:

    MIDDLEWARE_CLASSES = (
        'pathto.middleware.DecimalPrecisionMiddleware',
        # etc..
    )
    

提交回复
热议问题