Ticket #11206: 11206-floatformat-r14785.2.diff

File 11206-floatformat-r14785.2.diff, 2.5 KB (added by Tai Lee, 14 years ago)
  • django/template/defaultfilters.py

     
    168168    if p == 0:
    169169        exp = Decimal(1)
    170170    else:
    171         exp = Decimal('1.0') / (Decimal(10) ** abs(p))
     171        exp = Decimal(u'1.0') / (Decimal(10) ** abs(p))
    172172    try:
    173         return mark_safe(formats.number_format(u'%s' % str(d.quantize(exp, ROUND_HALF_UP)), abs(p)))
     173        # Avoid conversion to scientific notation by accessing `sign`, `digits`
     174        # and `exponent` from `Decimal.as_tuple()` directly.
     175        sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP).as_tuple()
     176        digits = [unicode(digit) for digit in reversed(digits)]
     177        while len(digits) <= abs(exponent):
     178            digits.append(u'0')
     179        digits.insert(-exponent, u'.')
     180        if sign:
     181            digits.append(u'-')
     182        number = u''.join(reversed(digits))
     183        return mark_safe(formats.number_format(number, abs(p)))
    174184    except InvalidOperation:
    175185        return input_val
    176186floatformat.is_safe = True
  • tests/regressiontests/defaultfilters/tests.py

     
    2929        self.assertEqual(floatformat(u'¿Cómo esta usted?'), u'')
    3030        self.assertEqual(floatformat(None), u'')
    3131
     32        # Check that we're not converting to scientific notation.
     33        self.assertEqual(floatformat(0, 10), u'0.0000000000')
     34        self.assertEqual(floatformat(0.000000000000000000015, 20),
     35                                     u'0.00000000000000000002')
     36
    3237        pos_inf = float(1e30000)
    3338        self.assertEqual(floatformat(pos_inf), unicode(pos_inf))
    3439
     
    4651
    4752        self.assertEqual(floatformat(FloatWrapper(11.000001), -2), u'11.00')
    4853
     54    # This fails because of Python's float handling. Floats with many zeroes
     55    # after the decimal point should be passed in as another type such as
     56    # unicode or Decimal.
     57    @unittest.expectedFailure
     58    def test_floatformat_fail(self):
     59        self.assertEqual(floatformat(1.00000000000000015, 16), u'1.0000000000000002')
     60
    4961    def test_addslashes(self):
    5062        self.assertEqual(addslashes(u'"double quotes" and \'single quotes\''),
    5163                          u'\\"double quotes\\" and \\\'single quotes\\\'')
Back to Top