diff --git a/apps/fyle/models.py b/apps/fyle/models.py index f1d106f0..fd33fe39 100644 --- a/apps/fyle/models.py +++ b/apps/fyle/models.py @@ -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 @@ -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 @@ -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'], diff --git a/tests/test_fyle/test_models.py b/tests/test_fyle/test_models.py index 8bde7478..e8c88891 100644 --- a/tests/test_fyle/test_models.py +++ b/tests/test_fyle/test_models.py @@ -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 @@ -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