Skip to content
Merged
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
5 changes: 3 additions & 2 deletions lib/money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ 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);
return dollarsToCents(String(value));
}

const text = String(value).trim().replace(/\s+/g, "");
if (!MONEY_RE.test(text)) return null;

const amount = Number(text.replace(/[$,]/g, ""));
if (!Number.isFinite(amount) || amount <= 0) return null;
return Math.round(amount * 100);
const cents = Math.round(amount * 100);
return cents > 0 ? cents : null;
}
3 changes: 3 additions & 0 deletions tests/money.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ test("dollarsToCents rejects partial or non-decimal strings", () => {

test("dollarsToCents handles numeric values without accepting non-finite numbers", () => {
assert.equal(dollarsToCents(2.5), 250);
assert.equal(dollarsToCents(1.23), 123);
assert.equal(dollarsToCents(1.234), null);
assert.equal(dollarsToCents(0.004), null);
assert.equal(dollarsToCents(Number.NaN), null);
assert.equal(dollarsToCents(Number.POSITIVE_INFINITY), null);
});
Loading