Skip to content

Commit

Permalink
Rounding off amount (#622)
Browse files Browse the repository at this point in the history
* Rounding off amount

* Add rounding for tax
  • Loading branch information
Hrishabh17 authored Jun 12, 2024
1 parent edbf7f8 commit 7f9119a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
10 changes: 8 additions & 2 deletions 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 Expand Up @@ -138,7 +144,7 @@ def create_expense_objects(expenses: List[Dict], workspace_id: int):
'currency': expense['currency'],
'foreign_amount': expense['foreign_amount'],
'foreign_currency': expense['foreign_currency'],
'tax_amount': expense['tax_amount'],
'tax_amount': _round_to_currency_fraction(expense['tax_amount'], expense['currency']) if expense['tax_amount'] else None,
'tax_group_id': expense['tax_group_id'],
'settlement_id': expense['settlement_id'],
'reimbursable': expense['reimbursable'],
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 7f9119a

Please sign in to comment.