Skip to content

Commit

Permalink
Merge pull request #13 from mmarta/master
Browse files Browse the repository at this point in the history
Added new currency field with two decimal place precision.
  • Loading branch information
miki725 committed Apr 20, 2017
2 parents ab6fec6 + df12919 commit 48c797f
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ Contributors

* Khaled Porlin - https://github.com/porlin72
* Agam Dua - https://github.com/agamdua
* Marc Marta - https://github.com/mmarta
20 changes: 20 additions & 0 deletions drf_braces/fields/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,23 @@ class NumericField(ValueAsTextFieldMixin, fields.IntegerField):

__all__ = [name for name, value in locals().items()
if inspect.isclass(value) and issubclass(value, fields.Field)]


class RoundedDecimalField(fields.DecimalField):
"""
Currency field subclass of Decimal used for rounding currencies
to two decimal places.
"""

def __init__(self, max_digits=100, decimal_places=2, *args, **kwargs):
super(fields.DecimalField, self).__init__(
max_digits=max_digits,
decimal_places=decimal_places,
*args, **kwargs
)

def to_internal_value(self, data):
return self.quantize(super(RoundedDecimalField, self).to_internal_value(data))

def validate_precision(self, data):
return data
15 changes: 15 additions & 0 deletions drf_braces/tests/fields/test_custom.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
from __future__ import print_function, unicode_literals
import unittest
from collections import OrderedDict
from decimal import Decimal

import mock
import pytz

from drf_braces.fields.custom import (
NonValidatingChoiceField,
PositiveIntegerField,
RoundedDecimalField,
UTCDateTimeField,
UnvalidatedField,
)
Expand Down Expand Up @@ -55,3 +57,16 @@ def test_to_internal_value(self):

self.assertEqual(field.to_internal_value('bar'), 'bar')
self.assertEqual(field.to_internal_value('haha'), 'haha')


class TestCurrencyField(unittest.TestCase):
def test_init(self):
field = RoundedDecimalField()
self.assertIsNotNone(field.max_digits)
self.assertEqual(field.decimal_places, 2)

def test_to_internal_value(self):
field = RoundedDecimalField()
self.assertEqual(field.to_internal_value(Decimal('5.2345')), Decimal('5.23'))
self.assertEqual(field.to_internal_value(Decimal('5.2356')), Decimal('5.24'))
self.assertEqual(field.to_internal_value(Decimal('4.2399')), Decimal('4.24'))

0 comments on commit 48c797f

Please sign in to comment.