Skip to content

Commit

Permalink
Allow constructing money from sub-units. (#5)
Browse files Browse the repository at this point in the history
* Allow constructing money from sub-units.

* Remove unnecessary rounding.

* Update README to document sub units conversion.

* Disable `too-many-public-methods` check in tests.
  • Loading branch information
raymondjavaxx authored and nickyr committed Oct 26, 2018
1 parent 732210b commit 94ef104
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
10 changes: 10 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ A Money object can be created with an amount (specified as a string) and a curre
>>> m
GBP 9.95
Money objects can also be created from and converted to sub units.

.. code:: python
>>> m = Money.from_sub_units(499, Currency.USD)
>>> m
USD 4.99
>>> m.sub_units
499
Money is immutable and supports most mathematical and logical operators.

.. code:: python
Expand Down
12 changes: 12 additions & 0 deletions money/money.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ def currency(self) -> Currency:

return self._currency

@classmethod
def from_sub_units(cls, sub_units: int, currency: Currency=Currency.USD):
"""Creates a Money instance from sub-units."""
sub_units_per_unit = CurrencyHelper.sub_unit_for_currency(currency)
return cls(Decimal(sub_units) / Decimal(sub_units_per_unit), currency)

@property
def sub_units(self) -> int:
"""Converts the amount to sub-units"""
sub_units_per_unit = CurrencyHelper.sub_unit_for_currency(self.currency)
return int(self.amount * sub_units_per_unit)

def __hash__(self) -> str:
return hash((self._amount, self._currency))

Expand Down
13 changes: 12 additions & 1 deletion money/tests/test_money.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from money.exceptions import InvalidAmountError, CurrencyMismatchError, InvalidOperandError

# pylint: disable=unneeded-not,expression-not-assigned,no-self-use,missing-docstring
# pylint: disable=misplaced-comparison-constant,singleton-comparison
# pylint: disable=misplaced-comparison-constant,singleton-comparison,too-many-public-methods

class TestMoney:
"""Money tests"""
Expand Down Expand Up @@ -36,6 +36,17 @@ def test_construction(self):
# nonfractional currency
Money('10.2', Currency.KRW)

def test_from_sub_units(self):
money = Money.from_sub_units(101, Currency.USD)
assert money == Money('1.01', Currency.USD)

money = Money.from_sub_units(5, Currency.JPY)
assert money == Money('5', Currency.JPY)

def test_sub_units(self):
money = Money('1.01', Currency.USD)
assert money.sub_units == 101

def test_hash(self):
assert hash(Money('1.2')) == hash(Money('1.2', Currency.USD))
assert hash(Money('1.5')) != hash(Money('9.3'))
Expand Down

0 comments on commit 94ef104

Please sign in to comment.