g1t/apps/sudo/app/lib/money.ts

35 lines1,736 bytesCodeBlame
1/** Money is held in micros: millionths of a dollar. */
2export const MICROS_PER_DOLLAR = 1_000_000;
3
4const WHOLE = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 });
5const SMALL = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 4 });
6
7/**
8 * Dollars, to the cent; amounts under a dollar keep up to four places, so
9 * a run that cost a fraction of a cent does not read as nothing. With
10 * `cents`, always to the cent: for statements, where figures sit in columns.
11 */
12export function usd(micros: number | null | undefined, { signed = false, cents = false }: { signed?: boolean; cents?: boolean } = {}): string {
13 if (micros == null) return "—";
14 const dollars = micros / MICROS_PER_DOLLAR;
15 const text = (Math.abs(dollars) < 1 && !cents ? SMALL : WHOLE).format(Math.abs(dollars));
16 if (dollars < 0) return `−${text}`;
17 return signed && dollars > 0 ? `+${text}` : text;
18}
19
20/**
21 * Micros from a dollar amount as typed: `25`, `25.5`, `$1,250.00`. Null
22 * unless it is a non-negative amount to the cent, under ten million.
23 */
24export function parseDollars(input: string): number | null {
25 const text = input.trim().replace(/^\$/, "").replace(/,/g, "");
26 const match = /^(\d{1,7})(?:\.(\d{1,2}))?$/.exec(text);
27 if (!match) return null;
28 const cents = Number((match[2] ?? "").padEnd(2, "0"));
29 return Number(match[1]) * MICROS_PER_DOLLAR + cents * 10_000;
30}
31
32/** A micros amount as dollars for a form field: `1250.5` → `"1250.50"`. */
33export function dollarsField(micros: number | null | undefined): string {
34 return micros == null ? "" : (micros / MICROS_PER_DOLLAR).toFixed(2);
35}