DEV Community

Keep the currency code attached when importing money from CSV

This article and its synthetic code example were drafted with AI assistance.

An export with USD 12.40 and EUR 12.40 has two currency balances. Summing the numeric column produces 24.80, a number with no currency. A safer importer keeps the currency code alongside the parsed decimal and produces one subtotal per currency.

Set the input contract before parsing

This example accepts USD and EUR with up to two decimal places, a period as the decimal separator and up to 12 digits before the separator.

It rejects:

  • comma separators
  • scientific notation
  • empty amounts

The importer can keep the original row and failure reason for review, then rerun a corrected row explicitly.

Example importer

import re
from decimal import Decimal

AMOUNT = re.compile(r"[+-]?[0-9]{1,12}(?:\.[0-9]{1,2})?")

def parse_money(currency: str, raw_amount: str) -> tuple[str, Decimal]:
    code = currency.strip().upper()
    if code not in {"USD", "EUR"}:
        raise ValueError("unsupported currency")
    value = raw_amount.strip()
    if not AMOUNT.fullmatch(value):
        raise ValueError("invalid amount for this import")
    return code, Decimal(value)

rows = [("USD", "12.40"), ("EUR", "12.40"), ("USD", "-2.05")]

totals: dict[str, Decimal] = {}
for currency, amount in rows:
    code, value = parse_money(currency, amount)
    totals[code] = totals.get(code, Decimal("0.00")) + value

assert totals == {"USD": Decimal("10.35"), "EUR": Decimal("12.40")}

Exercise the rejection path

("USD", "1,20") is ambiguous under this import contract. ("USD", "0.001") has too much precision. A blank currency is missing information and should never inherit the previous row's currency.

Multicurrency reporting total

For a multicurrency reporting total, apply a separately defined exchange rate, valuation date and rounding policy while retaining the source amounts.

Reference: Python documentation for Decimal.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.