From 9d1a69579b996eaa208f141b409141be63f597ec Mon Sep 17 00:00:00 2001 From: Eric Rouleau Date: Sun, 30 Nov 2014 03:29:52 -0500 Subject: [PATCH] Fixed #23935 -- Converted decimals to fixed point in utils.numberformat.format --- django/utils/numberformat.py | 7 ++++++- tests/utils_tests/test_numberformat.py | 15 +++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/django/utils/numberformat.py b/django/utils/numberformat.py index 6a31237f135..c3cf55bca5f 100644 --- a/django/utils/numberformat.py +++ b/django/utils/numberformat.py @@ -1,3 +1,5 @@ +from decimal import Decimal + from django.conf import settings from django.utils.safestring import mark_safe from django.utils import six @@ -22,7 +24,10 @@ def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', return mark_safe(six.text_type(number)) # sign sign = '' - str_number = six.text_type(number) + if isinstance(number, Decimal): + str_number = '{:f}'.format(number) + else: + str_number = six.text_type(number) if str_number[0] == '-': sign = '-' str_number = str_number[1:] diff --git a/tests/utils_tests/test_numberformat.py b/tests/utils_tests/test_numberformat.py index f9d9031e488..80f222d9555 100644 --- a/tests/utils_tests/test_numberformat.py +++ b/tests/utils_tests/test_numberformat.py @@ -1,6 +1,8 @@ -from unittest import TestCase -from django.utils.numberformat import format as nformat +from decimal import Decimal from sys import float_info +from unittest import TestCase + +from django.utils.numberformat import format as nformat class TestNumberFormat(TestCase): @@ -45,3 +47,12 @@ class TestNumberFormat(TestCase): self.assertEqual(nformat(0 - int_max, '.'), most_max.format('-', '8')) self.assertEqual(nformat(-1 - int_max, '.'), most_max.format('-', '9')) self.assertEqual(nformat(-2 * int_max, '.'), most_max2.format('-')) + + def test_decimal_numbers(self): + self.assertEqual(nformat(Decimal('1234'), '.'), '1234') + self.assertEqual(nformat(Decimal('1234.2'), '.'), '1234.2') + self.assertEqual(nformat(Decimal('1234'), '.', decimal_pos=2), '1234.00') + self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=','), '1234') + self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34') + self.assertEqual(nformat(Decimal('-1234.33'), '.', decimal_pos=1), '-1234.3') + self.assertEqual(nformat(Decimal('0.00000001'), '.', decimal_pos=8), '0.00000001')