From ca7cace03eb7a9777a5f8551a4f13d60b262d203 Mon Sep 17 00:00:00 2001 From: Tyler Grunenwald Date: Fri, 6 Dec 2024 09:51:46 -0600 Subject: [PATCH] fix: correctly parse dollars and cents from string representation --- features/steps/currency.py | 2 +- src/ddd_sample/domain/currency.py | 15 ++++++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/features/steps/currency.py b/features/steps/currency.py index f3c7ebe..ce24d10 100644 --- a/features/steps/currency.py +++ b/features/steps/currency.py @@ -33,6 +33,6 @@ def _(context): context.currency = Currency(value=USD.toValue(context.repr), format=USD) -@then("the resulting currency object has value {value}") +@then("the resulting currency object has value {value:d}") def _(context, value: int): assert context.currency.value == value, f"{context.currency.value} != {value}" diff --git a/src/ddd_sample/domain/currency.py b/src/ddd_sample/domain/currency.py index 45bfdb4..95e5071 100644 --- a/src/ddd_sample/domain/currency.py +++ b/src/ddd_sample/domain/currency.py @@ -17,12 +17,17 @@ class USD(CurrencyFormatMixin): def toValue(cls, repr: str) -> int: repr = repr.strip() repr = repr.replace(",", "") - match = re.search(r"^\$(\d*)\.?(\d?\d?)$", repr) - print(match.groups()) -# dollars = int(match.group(1)) -# cents = int(match.group(2)) + groups = re.search(r"^\$(\d*)\.?(\d?\d?)$", repr).groups() - return 0#dollars * 100 + cents + dollars_str = groups[0] + dollars = int(dollars_str) if dollars_str else 0 + + cents_str = groups[1] + if cents_str and 1 == len(cents_str): + cents_str += '0' + cents = int(cents_str) if cents_str else 0 + + return dollars * 100 + cents @abstractclassmethod def toString(cls, value: int) -> str: