Create a function to format amount with Intl native api
// number interface NumberFormatOptions { currencyDisplay?: Intl.NumberFormatOptions["currencyDisplay"]; style?: Intl.NumberFormatOptions["style"]; currency?: Intl.NumberFormatOptions["currency"]; locale?: string; } export function formatAmount(amount: string, options?: NumberFormatOptions) { const { currency = "USD", currencyDisplay = "narrowSymbol", style = "currency", locale = undefined } = options || {}; const amountFloat = parseFloat(amount); if (isNaN(amountFloat)) { throw new Error(`Invalid amount: "${amount}"`); } const formatter = new Intl.NumberFormat(locale, { style, currency, currencyDisplay, }); return formatter.format(amountFloat); } export const numberFormat = new Intl.NumberFormat("en-US", { notation: "compact", }); export const timeFormatter = new Intl.RelativeTimeFormat("en-US", { style: "long", });
// number.test.ts import { formatAmount } from "./number"; describe("formatAmount", () => { it("should format amount with default options", () => { const amount = "123.45"; const result = formatAmount(amount); expect(result).toBe("$123.45"); }); it("should format amount with custom currency", () => { const amount = "123.45"; const options = { currency: "EUR" }; const result = formatAmount(amount, options); expect(result).toBe("€123.45"); }); it("should format amount with custom currency display", () => { const amount = "123.45"; const result = formatAmount(amount, { currencyDisplay: "symbol" }); expect(result).toBe("$123.45"); }); it("should format amount with custom style", () => { const amount = "123.45"; const result = formatAmount(amount, { style: "decimal" }); expect(result).toBe("123.45"); }); it("should throw an error with invalid amount", () => { const amount = "abc"; expect(() => formatAmount(amount)).toThrowError(); }); it("should not throw an error with missing options", () => { const amount = "123.45"; expect(() => formatAmount(amount)).not.toThrowError(); }); });
189 views