pagamio-frontend-commons-lib
Version:
Pagamio library for Frontend reusable components like the form engine and table container
54 lines (53 loc) • 1.88 kB
JavaScript
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs) {
return twMerge(clsx(inputs));
}
/**
* Formats a number as currency with flexible localization options.
*
* @param {number} price - The numeric value to format as currency
* @param {string} [currency="ZAR"] - ISO 4217 currency code (default: "ZAR")
* @param {string} [locale="en-ZA"] - BCP 47 language tag (default: "en-ZA")
* @param {number} [minimumFractionDigits=0] - Minimum fraction digits (default: 0)
* @param {number} [maximumFractionDigits] - Optional maximum fraction digits
* @returns {string} Formatted currency string
*
* @example
* // Basic usage with ZAR (South African Rand)
* formatPrice(1234.56); // Returns "R 1,235" (en-ZA locale)
*
* @example
* // USD with 2 decimal places
* formatPrice(1234.56, "USD", "en-US", 2); // Returns "$1,234.56"
*
* @example
* // Euro with German formatting
* formatPrice(1234.56, "EUR", "de-DE", 2); // Returns "1.234,56 €"
*
* @example
* // Custom decimal places (clamping)
* formatPrice(1234.5678, "GBP", "en-GB", 2, 3); // Returns "£1,234.568"
*
* @example
* // Fallback behavior with invalid currency
* formatPrice(1234.56, "XYZ"); // Returns "XYZ 1235"
*/
export const formatPrice = (price, currency = 'ZAR', locale = 'en-ZA', minimumFractionDigits = 2, maximumFractionDigits) => {
const options = {
style: 'currency',
currency,
minimumFractionDigits,
};
if (maximumFractionDigits !== undefined) {
options.maximumFractionDigits = maximumFractionDigits;
}
try {
return price.toLocaleString(locale, options);
}
catch (error) {
console.error('Error formatting currency:', error);
// Fallback to basic formatting when Intl fails
return `${currency} ${price.toFixed(minimumFractionDigits)}`;
}
};