Money must never be stored as an approximate decimal. Parse amounts into whole cents, rejecting anything malformed, and add them up exactly.
What to build
A program that parses amounts into cents and totals the valid ones.
Requirements
- Write
parseCents(text: string): Result<number>accepting a whole number of units with an optional.and one or two decimal digits (for example12,12.5,0.05). - For each line print
TEXT -> C centsorTEXT -> error: not an amount. - Finally print
total: U.CC(the valid amounts added, with two decimals).
Input
Line 1: n. Then n lines.
Output
n lines, then the total.
Constraints
1 ≤ n ≤ 50; amounts are below 10^9 units.
Example
Input:
4
12.5
0.05
abc
3
Output:
12.5 -> 1250 cents
0.05 -> 5 cents
abc -> error: not an amount
3 -> 300 cents
total: 15.55
Why it works
Working in whole cents keeps every sum exact, and a Result makes the caller handle a bad amount before it can reach the total.
Examples
Example 1 · Input
4 12.5 0.05 abc 3
Expected output
12.5 -> 1250 cents 0.05 -> 5 cents abc -> error: not an amount 3 -> 300 cents total: 15.55
Example 2 · Input
3 0.1 0.2 1.234
Expected output
0.1 -> 10 cents 0.2 -> 20 cents 1.234 -> error: not an amount total: 0.30
Hints
Hint 1
type Result<T> = { ok: true; value: T } | { ok: false; error: string }.
Hint 2
Work in whole cents: 12.5 is 1250 cents. A regular expression can check the format.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function parseCents(text: string): Result<number> {
const m = /^(\d+)(?:\.(\d{1,2}))?$/.exec(text);
if (!m) return { ok: false, error: "not an amount" };
const cents = (m[2] ?? "").padEnd(2, "0");
return { ok: true, value: Number(m[1]) * 100 + Number(cents) };
}
const n = Number(read());
let total = 0;
for (let i = 0; i < n; i++) {
const text = read();
const r = parseCents(text);
if (r.ok) {
total += r.value;
console.log(text + " -> " + r.value + " cents");
} else {
console.log(text + " -> error: " + r.error);
}
}
console.log("total: " + Math.floor(total / 100) + "." + String(total % 100).padStart(2, "0"));