Commit d015e4b1 authored by Kazuhiko Shiozaki's avatar Kazuhiko Shiozaki

RoundingTool: add a utility round() method that supports rounding option.

parent f41b33cd
......@@ -55,6 +55,23 @@ class TestRoundingTool(ERP5TypeTestCase):
user_folder._doAddUser('assignor', '', ['Auditor', 'Author', 'Assignor'], [])
self.tic()
def testRoundMethod(self):
"""
Test round utility method
"""
rounding_tool = self.portal.portal_roundings
round = rounding_tool.round
self.assertEqual(round(500 * 655.957, 0), 327979.0)
self.assertEqual(round(-0.5), -1)
self.assertEqual(round(0.15, 1), 0.2)
self.assertEqual(round(-0.15, 1), -0.2)
self.assertEqual(round(1.25, 1), 1.3)
self.assertEqual(round(500 * 655.957, 0, 'ROUND_HALF_EVEN'), 327978.0)
self.assertEqual(round(-0.5, 0, 'ROUND_HALF_EVEN'), -0.0)
self.assertEqual(round(0.15, 1, 'ROUND_HALF_EVEN'), 0.2)
self.assertEqual(round(-0.15, 1, 'ROUND_HALF_EVEN'), -0.2)
self.assertEqual(round(1.25, 1, 'ROUND_HALF_EVEN'), 1.2)
def testRoundValueMethod(self):
"""
Test rounding method
......
......@@ -30,7 +30,7 @@ import zope.interface
from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Tool.BaseTool import BaseTool
from erp5.component.interface.IRoundingTool import IRoundingTool
from decimal import (ROUND_DOWN, ROUND_UP, ROUND_CEILING, ROUND_FLOOR,
from decimal import (Decimal, ROUND_DOWN, ROUND_UP, ROUND_CEILING, ROUND_FLOOR,
ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP)
ROUNDING_OPTION_DICT = {'ROUND_DOWN':ROUND_DOWN,
......@@ -41,6 +41,24 @@ ROUNDING_OPTION_DICT = {'ROUND_DOWN':ROUND_DOWN,
'ROUND_HALF_EVEN':ROUND_HALF_EVEN,
'ROUND_HALF_UP':ROUND_HALF_UP}
def round(value, ndigits=None, decimal_rounding_option='ROUND_HALF_UP'):
if ndigits is None:
precision = 1
else:
assert isinstance(ndigits, int), 'ndigits should be int.'
precision = 10 ** -ndigits
if precision >= 1:
value = Decimal(str(value))
value /= precision
value = value.quantize(precision, rounding=decimal_rounding_option)
value *= precision
result = float(value.quantize(precision))
else:
result = float(
Decimal(str(value)).quantize(Decimal(str(precision)),
rounding=decimal_rounding_option))
return result
@zope.interface.implementer(IRoundingTool)
class RoundingTool(BaseTool):
"""Rounding Tool"""
......@@ -113,3 +131,7 @@ class RoundingTool(BaseTool):
by python standard decimal module.
"""
return ROUNDING_OPTION_DICT.items()
security.declarePublic('round')
def round(self, value, ndigits=None, decimal_rounding_option='ROUND_HALF_UP'):
return round(value, ndigits, decimal_rounding_option)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment