Fix the dollar amount parser behind a passing test
Your task
An AI added a unit test for your ParseAmount function, which turns dollar strings like $12.34 into cents. The test passed, but it only ever tried well-formed amounts, so it could not fail. Your team's review writes down the parser's full contract and checks the code against it.
An assistant wrote parse_amount_cents(s). It is in the editor. It has a bug. Find it and fix it.
Input and output:
s: the amount as text.- Return the amount in cents as an integer written as a string, with no leading zeros and a leading
-when it is negative, or"error".
Rules the tests check:
- An optional
-at the very start makes the amount negative. A$must come next. Without it, return"error". - After the
$comes the dollar part, then optionally a.and exactly 2 digits of cents. With no., the cents are 00. Any other number of characters after the., or anything but digits 0 to 9 there, is an error. - The dollar part is one or more digits 0 to 9, which may be grouped with commas as thousands separators. With commas, the first group has 1 to 3 digits and every later group has exactly 3. An empty group, a group of the wrong size or any other character is an error.
- Leading zeros in the dollar part are allowed.
- Minus zero is written
"0".
Examples
parse_amount_cents(s: str) -> strExample 1
Input
parse_amount_cents("$12.34")Output
"1234"Example 2
Input
parse_amount_cents("$5")Output
"500"Example 3
Input
parse_amount_cents("$1,000.00")Output
"100000"