From c7a612e72cb2c82aaff5b8ec66bf3cae88571db5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Krier?= Date: Wed, 7 Aug 2019 19:18:48 +0200 Subject: [PATCH] Ensure precision is great enough when rounding The quantize method raise InvalidOperation if the length of the coefficient after the quantize operation would be greater than precision. issue6534 review255701002 --- currency.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/currency.py b/currency.py index 7bde4d4a07..106139ec65 100644 --- a/currency.py +++ b/currency.py @@ -2,7 +2,7 @@ # this repository contains the full copyright notices and license terms. import datetime -from decimal import Decimal, ROUND_HALF_EVEN +from decimal import Decimal, ROUND_HALF_EVEN, localcontext from sql import Window from sql.functions import NthValue @@ -143,8 +143,12 @@ class Currency(DeactivableMixin, ModelSQL, ModelView): def round(self, amount, rounding=ROUND_HALF_EVEN): 'Round the amount depending of the currency' - return (amount / self.rounding).quantize(Decimal('1.'), - rounding=rounding) * self.rounding + with localcontext() as ctx: + ctx.prec = max(ctx.prec, (amount / self.rounding).adjusted() + 1) + # Divide and multiple by rounding for case rounding is not 10En + result = (amount / self.rounding).quantize(Decimal('1.'), + rounding=rounding) * self.rounding + return Decimal(result) def is_zero(self, amount): 'Return True if the amount can be considered as zero for the currency'