Allow rounding with opposite method

This commit is contained in:
Nicolas Évrard committed 2022-12-25 18:54:30 +01:00
1 parent eddb82a7a1
commit 458f6b0327
3 files changed
+42 -3

No files matched your search

+2
View File
@@ -1,3 +1,5 @@
* Allow rounding with opposite method
Version 6.6.0 - 2022-10-31
--------------------------
* Bug fixes (see mercurial logs for details)
+16 -2
View File
@@ -1,8 +1,9 @@
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import datetime
import decimal
import logging
from decimal import ROUND_HALF_EVEN, Decimal, localcontext
from decimal import Decimal, localcontext
from dateutil.relativedelta import relativedelta
from sql import Window
@@ -24,6 +25,17 @@ from .ir import rate_decimal
logger = logging.getLogger(__name__)
ROUNDING_OPPOSITES = {
decimal.ROUND_HALF_EVEN: decimal.ROUND_HALF_EVEN,
decimal.ROUND_HALF_UP: decimal.ROUND_HALF_DOWN,
decimal.ROUND_HALF_DOWN: decimal.ROUND_HALF_UP,
decimal.ROUND_UP: decimal.ROUND_DOWN,
decimal.ROUND_DOWN: decimal.ROUND_UP,
decimal.ROUND_CEILING: decimal.ROUND_FLOOR,
decimal.ROUND_FLOOR: decimal.ROUND_CEILING,
}
class Currency(
SymbolMixin, DigitsMixin, DeactivableMixin, ModelSQL, ModelView):
'Currency'
@@ -148,8 +160,10 @@ class Currency(
res[currency_id] = id2rate[res[currency_id]].rate
return res
def round(self, amount, rounding=ROUND_HALF_EVEN):
def round(self, amount, rounding=decimal.ROUND_HALF_EVEN, opposite=False):
'Round the amount depending of the currency'
if opposite:
rounding = ROUNDING_OPPOSITES[rounding]
return self._round(amount, self.rounding, rounding)
@classmethod
+24 -1
View File
@@ -3,7 +3,7 @@
import datetime
import unittest
from decimal import Decimal
from decimal import ROUND_HALF_DOWN, Decimal
from trytond import backend
from trytond.modules.currency.ecb import (
@@ -143,6 +143,29 @@ class CurrencyTestCase(ModuleTestCase):
self.assertEqual(rounded, Decimal('1.2345'))
@with_transaction()
def test_round_opposite(self):
"Test the opposite rounding"
cu = create_currency('cu')
cu.save()
rounded = cu.round(Decimal('1.235'))
self.assertEqual(rounded, Decimal('1.24'))
opposite_rounded = cu.round(Decimal('1.235'), opposite=True)
self.assertEqual(opposite_rounded, Decimal('1.24'))
@with_transaction()
def test_round_opposite_HALF_DOWN(self):
"Test the oposite rounding of ROUND_HALF_DOWN"
cu = create_currency('cu')
cu.save()
rounded = cu.round(Decimal('1.235'), rounding=ROUND_HALF_DOWN)
self.assertEqual(rounded, Decimal('1.23'))
opposite_rounded = cu.round(
Decimal('1.235'), rounding=ROUND_HALF_DOWN, opposite=True)
self.assertEqual(opposite_rounded, Decimal('1.24'))
@with_transaction()
def test_is_zero(self):
"Test is zero"