diff options
author | Stephan Richter <stephan.richter@gmail.com> | 2017-05-23 10:17:09 -0400 |
---|---|---|
committer | Stephan Richter <stephan.richter@gmail.com> | 2017-05-23 10:17:09 -0400 |
commit | 63e752a934476377e9d7c01401f53d042e357725 (patch) | |
tree | c2ee28b2b8769cb4314df328f3b496b6d130c381 | |
parent | 43e7f5e5fdd1a54dbb93272cb16bcb2b733297df (diff) | |
download | zope-i18n-63e752a934476377e9d7c01401f53d042e357725.tar.gz |
Handled @mgedmin's original concern about high-precision numbers (in contrast to really small numbers).
-rw-r--r-- | src/zope/i18n/format.py | 10 | ||||
-rw-r--r-- | src/zope/i18n/tests/test_formats.py | 16 |
2 files changed, 25 insertions, 1 deletions
diff --git a/src/zope/i18n/format.py b/src/zope/i18n/format.py index 055869e..494d09c 100644 --- a/src/zope/i18n/format.py +++ b/src/zope/i18n/format.py @@ -31,6 +31,9 @@ from ._compat import _u PY3 = sys.version_info[0] == 3 if PY3: unicode = str + NATIVE_NUMBER_TYPES = (int, float) +else: + NATIVE_NUMBER_TYPES = (int, float, long) def roundHalfUp(n): """Works like round() in python2.x @@ -372,7 +375,12 @@ class NumberFormat(object): else: bin_pattern = bin_pattern[1] - strobj = str(obj) + if isinstance(obj, NATIVE_NUMBER_TYPES): + # repr() handles high-precision numbers correctly in + # Python 2 and 3. str() is only correct in Python 3. + strobj = repr(obj) + else: + strobj = str(obj) if 'e' in strobj: # Str(obj) # returned scientific representation of a number (e.g. # 1e-7). We can't rely on str() to format fraction. diff --git a/src/zope/i18n/tests/test_formats.py b/src/zope/i18n/tests/test_formats.py index 9f48fdb..ce235c3 100644 --- a/src/zope/i18n/tests/test_formats.py +++ b/src/zope/i18n/tests/test_formats.py @@ -1180,6 +1180,22 @@ class TestNumberFormat(TestCase): self.assertEqual(self.format.format( -1e-7, '(#0.00#####);(-#0.00#####)'), '(-0.0000001)') self.assertEqual(self.format.format(1e-9, '(#0.00###)'), '(0.00)') + self.assertEqual(self.format.format(1e-9, '(#0.00###)'), '(0.00)') + + def testFormatHighPrecisionNumbers(self): + self.assertEqual(self.format.format( + 1+1e-7, '(#0.00#####);(-#0.00#####)'), '(1.0000001)') + self.assertEqual(self.format.format( + 1+1e-7, '(#0.00###)'), '(1.00000)') + self.assertEqual(self.format.format( + 1+1e-9, '(#0.00#######);(-#0.00#######)'), '(1.000000001)') + self.assertEqual(self.format.format( + 1+1e-9, '(#0.00###)'), '(1.00000)') + self.assertEqual(self.format.format( + 1+1e-12, '(#0.00##########);(-#0.00##########)'), + '(1.000000000001)') + self.assertEqual(self.format.format( + 1+1e-12, '(#0.00###)'), '(1.00000)') def testNoRounding(self): # Witout Rounding |