Ticket #15789: patch.diff

File patch.diff, 2.1 KB (added by Jose Ignacio Galarza, 14 years ago)

Patch

  • django/template/defaultfilters.py

    diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
    index 60fa59e..7d4af06 100644
    a b  
    22
    33import re
    44import random as random_module
    5 from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
     5from decimal import Decimal, InvalidOperation, Context, ROUND_HALF_UP
    66from functools import wraps
    77
    88from django.template.base import Variable, Library
    def floatformat(text, arg=-1):  
    148148    else:
    149149        exp = Decimal(u'1.0') / (Decimal(10) ** abs(p))
    150150    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
    151155        # Avoid conversion to scientific notation by accessing `sign`, `digits`
    152156        # 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
    154160        digits = [unicode(digit) for digit in reversed(digits)]
    155161        while len(digits) <= abs(exponent):
    156162            digits.append(u'0')
  • tests/regressiontests/defaultfilters/tests.py

    diff --git a/tests/regressiontests/defaultfilters/tests.py b/tests/regressiontests/defaultfilters/tests.py
    index 286c7f8..334a1e4 100644
    a b  
    11# -*- coding: utf-8 -*-
    22import datetime
     3import decimal
    34from django.utils import unittest
    45
    56from django.template.defaultfilters import *
    class DefaultFiltersTests(unittest.TestCase):  
    5354
    5455        self.assertEqual(floatformat(FloatWrapper(11.000001), -2), u'11.00')
    5556
     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
    5662    # This fails because of Python's float handling. Floats with many zeroes
    5763    # after the decimal point should be passed in as another type such as
    5864    # unicode or Decimal.
Back to Top