diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
index 3606942..945cc17 100644
a
|
b
|
|
3 | 3 | import re |
4 | 4 | import random as random_module |
5 | 5 | import unicodedata |
6 | | from decimal import Decimal, InvalidOperation, ROUND_HALF_UP |
| 6 | from decimal import Decimal, InvalidOperation, Context, ROUND_HALF_UP |
7 | 7 | from functools import wraps |
8 | 8 | from pprint import pformat |
9 | 9 | |
… |
… |
def floatformat(text, arg=-1):
|
156 | 156 | else: |
157 | 157 | exp = Decimal(u'1.0') / (Decimal(10) ** abs(p)) |
158 | 158 | try: |
| 159 | # Set the precission to the necessary digits to avoid an exception. |
| 160 | units = d.adjusted() |
| 161 | units = 1 if units < 0 else units |
| 162 | prec = abs(arg) + units + 1 |
| 163 | |
159 | 164 | # Avoid conversion to scientific notation by accessing `sign`, `digits` |
160 | 165 | # and `exponent` from `Decimal.as_tuple()` directly. |
161 | | sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP).as_tuple() |
| 166 | sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP, |
| 167 | Context(prec=prec)).as_tuple() |
162 | 168 | digits = [unicode(digit) for digit in reversed(digits)] |
163 | 169 | while len(digits) <= abs(exponent): |
164 | 170 | digits.append(u'0') |
diff --git a/tests/regressiontests/defaultfilters/tests.py b/tests/regressiontests/defaultfilters/tests.py
index cbd4776..ec4a260 100644
a
|
b
|
|
1 | 1 | # -*- coding: utf-8 -*- |
2 | 2 | from __future__ import with_statement |
3 | 3 | import datetime |
| 4 | import decimal |
4 | 5 | from django.test import TestCase |
5 | 6 | from django.utils import unittest, translation |
6 | 7 | |
… |
… |
class DefaultFiltersTests(TestCase):
|
18 | 19 | self.assertEqual(floatformat(7.7, 3), u'7.700') |
19 | 20 | self.assertEqual(floatformat(6.000000, 3), u'6.000') |
20 | 21 | self.assertEqual(floatformat(6.200000, 3), u'6.200') |
| 22 | self.assertEqual(floatformat(5555.555, 2), u'5555.56') |
| 23 | self.assertEqual(floatformat(001.3000, 2), u'1.30') |
21 | 24 | self.assertEqual(floatformat(6.200000, -3), u'6.200') |
22 | 25 | self.assertEqual(floatformat(13.1031, -3), u'13.103') |
23 | 26 | self.assertEqual(floatformat(11.1197, -2), u'11.12') |
… |
… |
class DefaultFiltersTests(TestCase):
|
31 | 34 | self.assertEqual(floatformat(u'¿Cómo esta usted?'), u'') |
32 | 35 | self.assertEqual(floatformat(None), u'') |
33 | 36 | |
| 37 | # Ignore the precision of decimal context. |
| 38 | decimal.getcontext().prec = 2 |
| 39 | self.assertEqual(floatformat(1.2345, 2), u'1.23') |
| 40 | self.assertEqual(floatformat(15.2042, -3), u'15.204') |
| 41 | |
34 | 42 | # Check that we're not converting to scientific notation. |
35 | 43 | self.assertEqual(floatformat(0, 6), u'0.000000') |
36 | 44 | self.assertEqual(floatformat(0, 7), u'0.0000000') |