69 lines
1.8 KiB
TypeScript
69 lines
1.8 KiB
TypeScript
/**
|
|
* Currency utilities for formatting amounts with proper symbols
|
|
*/
|
|
|
|
// Currency symbols map
|
|
const CURRENCY_SYMBOLS: Record<string, string> = {
|
|
USD: '$',
|
|
EUR: '€',
|
|
GBP: '£',
|
|
INR: '₹',
|
|
JPY: '¥',
|
|
CNY: '¥',
|
|
AUD: 'A$',
|
|
CAD: 'C$',
|
|
CHF: 'Fr',
|
|
SEK: 'kr',
|
|
NOK: 'kr',
|
|
DKK: 'kr',
|
|
PLN: 'zł',
|
|
BRL: 'R$',
|
|
ZAR: 'R',
|
|
AED: 'د.إ',
|
|
SAR: 'ر.س',
|
|
PKR: '₨',
|
|
};
|
|
|
|
/**
|
|
* Get currency symbol for a currency code
|
|
*/
|
|
export const getCurrencySymbol = (currencyCode?: string): string => {
|
|
if (!currencyCode) return '$';
|
|
const code = currencyCode.toUpperCase();
|
|
return CURRENCY_SYMBOLS[code] || `${code} `;
|
|
};
|
|
|
|
/**
|
|
* Format an amount with the proper currency symbol
|
|
* @param amount - The amount to format (string or number)
|
|
* @param currency - The currency code (e.g., 'USD', 'PKR')
|
|
* @param showDecimals - Whether to show decimal places (default: true for most currencies)
|
|
*/
|
|
export const formatCurrency = (
|
|
amount: string | number,
|
|
currency?: string,
|
|
showDecimals: boolean = true
|
|
): string => {
|
|
const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
|
|
if (isNaN(numAmount)) return '-';
|
|
|
|
const symbol = getCurrencySymbol(currency);
|
|
|
|
// For zero-decimal currencies like JPY, don't show decimals
|
|
const zeroDecimalCurrencies = ['JPY', 'KRW', 'VND'];
|
|
const shouldShowDecimals = showDecimals && !zeroDecimalCurrencies.includes(currency?.toUpperCase() || '');
|
|
|
|
const formatted = shouldShowDecimals
|
|
? numAmount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
|
: numAmount.toLocaleString('en-US', { maximumFractionDigits: 0 });
|
|
|
|
return `${symbol}${formatted}`;
|
|
};
|
|
|
|
/**
|
|
* Format price for display (typically USD)
|
|
*/
|
|
export const formatPrice = (price: string | number): string => {
|
|
return formatCurrency(price, 'USD');
|
|
};
|