diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
index 60fa59e..7d4af06 100644
a
|
b
|
|
2 | 2 | |
3 | 3 | import re |
4 | 4 | import random as random_module |
5 | | from decimal import Decimal, InvalidOperation, ROUND_HALF_UP |
| 5 | from decimal import Decimal, InvalidOperation, Context, ROUND_HALF_UP |
6 | 6 | from functools import wraps |
7 | 7 | |
8 | 8 | from django.template.base import Variable, Library |
… |
… |
def floatformat(text, arg=-1):
|
148 | 148 | else: |
149 | 149 | exp = Decimal(u'1.0') / (Decimal(10) ** abs(p)) |
150 | 150 | try: |
| 151 | # Set the precission to the necessary digits to avoid an exception. |
| 152 | # Bigger of the number of digits and the number of actual decimals |
| 153 | prec = max(abs(arg) + 1, abs(d.as_tuple()[2]) + 1) |
| 154 | |
151 | 155 | # Avoid conversion to scientific notation by accessing `sign`, `digits` |
152 | 156 | # and `exponent` from `Decimal.as_tuple()` directly. |
153 | | sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP).as_tuple() |
| 157 | sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP, |
| 158 | Context(prec=prec)).as_tuple() |
| 159 | |
154 | 160 | digits = [unicode(digit) for digit in reversed(digits)] |
155 | 161 | while len(digits) <= abs(exponent): |
156 | 162 | digits.append(u'0') |
diff --git a/tests/regressiontests/defaultfilters/tests.py b/tests/regressiontests/defaultfilters/tests.py
index 286c7f8..334a1e4 100644
a
|
b
|
|
1 | 1 | # -*- coding: utf-8 -*- |
2 | 2 | import datetime |
| 3 | import decimal |
3 | 4 | from django.utils import unittest |
4 | 5 | |
5 | 6 | from django.template.defaultfilters import * |
… |
… |
class DefaultFiltersTests(unittest.TestCase):
|
53 | 54 | |
54 | 55 | self.assertEqual(floatformat(FloatWrapper(11.000001), -2), u'11.00') |
55 | 56 | |
| 57 | decimal.getcontext().prec = 2 |
| 58 | self.assertEqual(floatformat(1.2345, 2), u'1.23') |
| 59 | self.assertEqual(floatformat(15.2042, -3), u'15.204') |
| 60 | |
| 61 | |
56 | 62 | # This fails because of Python's float handling. Floats with many zeroes |
57 | 63 | # after the decimal point should be passed in as another type such as |
58 | 64 | # unicode or Decimal. |