Global decimal rounding options in Django

后端 未结 4 794
生来不讨喜
生来不讨喜 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:30

    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
    

    Worked in 1.10. Based on my answer in this question.

提交回复
热议问题