54 lines
1.3 KiB
TypeScript
Raw Normal View History

/**
* Toolkit - Currency Formatting
*
* Utilities for formatting currency values.
*/
export type SupportedCurrency = "JPY" | "USD" | "EUR";
export interface CurrencyFormatOptions {
locale?: string;
showSymbol?: boolean;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
}
/**
* Format a number as currency
*/
export function formatCurrency(
amount: number,
currency: SupportedCurrency = "JPY",
options: CurrencyFormatOptions = {}
): string {
const {
locale = "en-US",
showSymbol = true,
minimumFractionDigits,
maximumFractionDigits,
} = options;
// JPY doesn't use decimal places
const defaultFractionDigits = currency === "JPY" ? 0 : 2;
const formatter = new Intl.NumberFormat(locale, {
style: showSymbol ? "currency" : "decimal",
currency: showSymbol ? currency : undefined,
minimumFractionDigits: minimumFractionDigits ?? defaultFractionDigits,
maximumFractionDigits: maximumFractionDigits ?? defaultFractionDigits,
});
return formatter.format(amount);
}
/**
* Parse a currency string to a number
*/
export function parseCurrency(value: string): number | null {
// Remove currency symbols, commas, and whitespace
const cleaned = value.replace(/[¥$€,\s]/g, "");
const parsed = Number.parseFloat(cleaned);
return Number.isFinite(parsed) ? parsed : null;
}