Files
gridpilot.gg/apps/website/lib/display-objects/CurrencyDisplay.ts
2026-01-19 00:46:46 +01:00

37 lines
1.1 KiB
TypeScript

/**
* CurrencyDisplay
*
* Deterministic currency formatting for display.
* Avoids Intl and toLocaleString to prevent SSR/hydration mismatches.
*/
export class CurrencyDisplay {
/**
* Formats an amount as currency (e.g., "$10.00").
* Default currency is USD.
*/
static format(amount: number, currency: string = 'USD'): string {
const symbol = currency === 'USD' ? '$' : currency + ' ';
const formattedAmount = amount.toFixed(2);
// Add thousands separators
const parts = formattedAmount.split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return `${symbol}${parts.join('.')}`;
}
/**
* Formats an amount as a compact currency (e.g., "$10").
*/
static formatCompact(amount: number, currency: string = 'USD'): string {
const symbol = currency === 'USD' ? '$' : currency + ' ';
const roundedAmount = Math.round(amount);
// Add thousands separators
const formattedAmount = roundedAmount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return `${symbol}${formattedAmount}`;
}
}