Sample work · Code & Bugs
Code Repair: A CSV Import That Reads Amounts Wrongly
A Python script read “1.234,50” from a German till export as 1.2345. Here are the cause, the fix and the test that locks the bug down from now on.
Sample work, not a client job. The business and all figures are invented, so you can see what the work looks like before you order anything.
The symptom
The monthly total from the till export was far too small. Some rows were missing altogether: the script stopped at amounts above 999 euros or read them as a decimal number.
The cause
The export writes amounts in the German format, with a dot as the thousands separator and a comma as the decimal separator. The script only replaced the comma with a dot. “1.234,50” became “1.234.50”, and that is not a number.
Before
def parse_amount(text):
return float(text.replace(",", ".")) # "1.234,50" -> "1.234.50" -> error or wrong value
After
def parse_amount(text: str) -> float:
"""German format from the till export: dot = thousands, comma = decimal."""
raw = text.strip().replace("\u00a0", "").replace(" €", "")
if "," in raw:
raw = raw.replace(".", "").replace(",", ".")
return round(float(raw), 2)
The test that locks the bug down
def test_german_amounts():
assert parse_amount("1.234,50") == 1234.50
assert parse_amount("0,99") == 0.99
assert parse_amount("12,00 €") == 12.00
assert parse_amount("250") == 250.00
Both are delivered: the fix and the test. If the bug comes back through a later change, the test fails before wrong figures end up in the bookkeeping.
Something like this for your business?
Describe briefly what you need. You get a fixed price before I start; nothing happens without your yes.