Skip to content

Commit

Permalink
Rounding off amount
Browse files Browse the repository at this point in the history
  • Loading branch information
Hrishabh17 committed Jun 11, 2024
1 parent edbf7f8 commit df85c7c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
8 changes: 7 additions & 1 deletion apps/fyle/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from collections import defaultdict
from datetime import datetime
from typing import Dict, List
from decimal import Decimal

from babel.numbers import get_currency_precision
from dateutil import parser
Expand Down Expand Up @@ -50,9 +51,14 @@ def _format_date(date_string) -> datetime:
return date_string


def round_amount(amount, fraction):
amount = Decimal(str(amount))
return float(amount.quantize(Decimal('1.' + '0' * fraction)))


def _round_to_currency_fraction(amount: float, currency: str) -> float:
fraction = get_currency_precision(currency) or 2
rounded_amount = round(amount, fraction)
rounded_amount = round_amount(amount, fraction)

return rounded_amount

Expand Down
18 changes: 18 additions & 0 deletions tests/test_fyle/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
get_default_expense_group_fields,
get_default_expense_state,
parser,
_round_to_currency_fraction
)
from tests.test_fyle.fixtures import data

Expand Down Expand Up @@ -326,3 +327,20 @@ def test_format_date():
date_string = _format_date('2022-05-13T09:32:06.643941Z')

assert date_string == parser.parse('2022-05-13T09:32:06.643941Z')


def test_amount_rounding():
amount = _round_to_currency_fraction(81.6455, 'USD')
assert amount == 81.65

amount = _round_to_currency_fraction(81.642, 'USD')
assert amount == 81.64

amount = _round_to_currency_fraction(81.6455, 'TND')
assert amount == 81.646

amount = _round_to_currency_fraction(81.64555, 'TND')
assert amount == 81.646

amount = _round_to_currency_fraction(81.64, 'JOD')
assert amount == 81.64

0 comments on commit df85c7c

Please sign in to comment.