Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@ export function dollarsToCents(value: unknown): number | null {
if (value === "" || value == null) return null;
if (typeof value === "number") {
if (!Number.isFinite(value) || value <= 0) return null;
return Math.round(value * 100);
// Reject sub-cent precision, exactly as the string path does via MONEY_RE's
// `\.\d{1,2}`. Without this a bare number like 1.234 silently rounds to 123,
// letting a partial dollar amount slip through the number path while the
// equivalent "$1.234" string is rejected.
const cents = value * 100;
if (Math.abs(cents - Math.round(cents)) > 1e-6) return null;
return Math.round(cents);
}

const text = String(value).trim().replace(/\s+/g, "");
Expand Down
12 changes: 12 additions & 0 deletions tests/money.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,15 @@ test("dollarsToCents handles numeric values without accepting non-finite numbers
assert.equal(dollarsToCents(Number.NaN), null);
assert.equal(dollarsToCents(Number.POSITIVE_INFINITY), null);
});

test("dollarsToCents rejects partial dollar amounts passed as numbers", () => {
// The number path must reject sub-cent precision just like the "$1.234"
// string case above — otherwise numeric JSON bodies bypass the guard.
assert.equal(dollarsToCents(1.234), null);
assert.equal(dollarsToCents(5.005), null);
assert.equal(dollarsToCents(0.999), null);
// Whole-cent numbers still parse, including exact two-decimal values.
assert.equal(dollarsToCents(1), 100);
assert.equal(dollarsToCents(1.99), 199);
assert.equal(dollarsToCents(1234.56), 123456);
});