diff --git a/src/pricehist/format.py b/src/pricehist/format.py index 0c9dcbe..64519f7 100644 --- a/src/pricehist/format.py +++ b/src/pricehist/format.py @@ -1,5 +1,4 @@ from dataclasses import dataclass -from decimal import Decimal, getcontext @dataclass(frozen=True) @@ -9,3 +8,9 @@ class Format: thousands: str = "" symbol: str = "rightspace" datesep: str = "-" + + def format_num(self, num): + parts = f"{num:,}".split(".") + parts[0] = parts[0].replace(",", self.thousands) + result = self.decimal.join(parts) + return result diff --git a/src/pricehist/outputs/beancount.py b/src/pricehist/outputs/beancount.py index 73bc2ef..13b9980 100644 --- a/src/pricehist/outputs/beancount.py +++ b/src/pricehist/outputs/beancount.py @@ -8,9 +8,8 @@ class Beancount(BaseOutput): lines = [] for price in series.prices: - amount_parts = f"{price.amount:,}".split(".") - amount_parts[0] = amount_parts[0].replace(",", fmt.thousands) - amount = ".".join(amount_parts) + amount = fmt.format_num(price.amount) + # TODO warn if fmt settings make an invalid number qa_parts = [amount] if fmt.symbol == "right": diff --git a/src/pricehist/outputs/csv.py b/src/pricehist/outputs/csv.py index 93013e8..b34aacb 100644 --- a/src/pricehist/outputs/csv.py +++ b/src/pricehist/outputs/csv.py @@ -8,9 +8,7 @@ class CSV(BaseOutput): lines = ["date,base,quote,amount,source,type"] for price in series.prices: date = str(price.date).replace("-", fmt.datesep) - amount_parts = f"{price.amount:,}".split(".") - amount_parts[0] = amount_parts[0].replace(",", fmt.thousands) - amount = fmt.decimal.join(amount_parts) + amount = fmt.format_num(price.amount) line = ",".join( [date, series.base, series.quote, amount, source.id(), series.type] ) diff --git a/src/pricehist/outputs/gnucashsql.py b/src/pricehist/outputs/gnucashsql.py index 61b40cc..bd29b17 100644 --- a/src/pricehist/outputs/gnucashsql.py +++ b/src/pricehist/outputs/gnucashsql.py @@ -29,6 +29,7 @@ class GnuCashSQL(BaseOutput): ).encode("utf-8") ) guid = m.hexdigest()[0:32] + # TODO extract this logic to a helper method value_num = str(price.amount).replace(".", "") value_denom = 10 ** len(f"{price.amount}.".split(".")[1]) v = ( diff --git a/src/pricehist/outputs/ledger.py b/src/pricehist/outputs/ledger.py index 8271b49..dfe2d22 100644 --- a/src/pricehist/outputs/ledger.py +++ b/src/pricehist/outputs/ledger.py @@ -9,9 +9,7 @@ class Ledger(BaseOutput): for price in series.prices: date = str(price.date).replace("-", fmt.datesep) - amount_parts = f"{price.amount:,}".split(".") - amount_parts[0] = amount_parts[0].replace(",", fmt.thousands) - amount = fmt.decimal.join(amount_parts) + amount = fmt.format_num(price.amount) qa_parts = [amount] if fmt.symbol == "left":