65 lines
1.9 KiB
TypeScript

/**
* Toolkit - Currency Formatting
*
* Simple currency formatting. Currency code comes from user's WHMCS profile.
* Typically JPY for this application.
*/
export type SupportedCurrency = "JPY" | "USD" | "EUR";
/**
* Format a number as currency using WHMCS default currency
*
* @param amount - The numeric amount to format
* @param currencyCode - Optional currency code (defaults to WHMCS default)
* @param locale - Optional locale (defaults to currency-specific locale)
*
* @example
* formatCurrency(1000) // Uses WHMCS default currency
* formatCurrency(1000, "USD") // Uses specific currency
* formatCurrency(1000, "JPY", "ja-JP") // Uses specific currency and locale
*/
export function formatCurrency(
amount: number,
currencyCode: string = "JPY",
locale?: string
): string {
// Use provided locale or get from currency
const currencyLocale = locale || getCurrencyLocale(currencyCode as SupportedCurrency);
// Determine fraction digits based on currency
const fractionDigits = currencyCode === "JPY" ? 0 : 2;
const formatter = new Intl.NumberFormat(currencyLocale, {
style: "currency",
currency: currencyCode,
minimumFractionDigits: fractionDigits,
maximumFractionDigits: fractionDigits,
});
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;
}
/**
* Get the locale string for a given currency
*/
export function getCurrencyLocale(currency: SupportedCurrency = "JPY"): string {
const localeMap: Record<SupportedCurrency, string> = {
JPY: "ja-JP",
USD: "en-US",
EUR: "de-DE",
};
return localeMap[currency] || "en-US";
}