Commits

Felix Schwarz committed 2dd9426

merge r611 from trunk

  • Participants
  • Parent commits 3265110
  • Branches stable-0.9.x

Comments (0)

Files changed (3)

+Version 0.9.7
+http://svn.edgewall.org/repos/babel/tags/0.9.7/
+(??? ?? 20??, from branches/stable/0.9.x)
+ * Only use bankers round algorithm as a tie breaker if there are two nearest
+   numbers, round as usual if there is only one nearest number (#267, patch by 
+   Martin)
+
+
 Version 0.9.6
 http://svn.edgewall.org/repos/babel/tags/0.9.6/
 (Mar 17 2011, from branches/stable/0.9.x)

File babel/numbers.py

         add = 1
     elif digits[i] == '5' and digits[i-1] in '13579':
         add = 1
+    elif digits[i] == '5':     # previous digit is even
+        # We round up unless all following digits are zero.
+        for j in xrange(i + 1, len(digits)):
+            if digits[j] != '0':
+                add = 1
+                break
+
     scale = 10**ndigits
     if have_decimal and isinstance(value, Decimal):
         return Decimal(int(value * scale + add)) / scale * sign

File babel/tests/numbers.py

         self.assertEqual(fmt, '0E0')
 
 
+class BankersRoundTestCase(unittest.TestCase):
+    def test_round_to_nearest_integer(self):
+        self.assertEqual(1, numbers.bankersround(0.5001))
+    
+    def test_round_to_even_for_two_nearest_integers(self):
+        self.assertEqual(0, numbers.bankersround(0.5))
+        self.assertEqual(2, numbers.bankersround(1.5))
+        self.assertEqual(-2, numbers.bankersround(-2.5))
+
+        self.assertEqual(0, numbers.bankersround(0.05, ndigits=1))
+        self.assertEqual(0.2, numbers.bankersround(0.15, ndigits=1))
+
+
 def suite():
     suite = unittest.TestSuite()
     suite.addTest(doctest.DocTestSuite(numbers))
     suite.addTest(unittest.makeSuite(FormatDecimalTestCase))
+    suite.addTest(unittest.makeSuite(BankersRoundTestCase))
     return suite
 
 if __name__ == '__main__':