function debounce(func, timeout = 300) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => { func.apply(this, args); }, timeout); }; } function formatField(elem) { const fs = new Map([ ["usd", { "locale": 'en-US', "style": 'currency', "currency": 'USD' }], ["gbp", { "locale": 'en-US', "style": 'currency', "currency": 'GBP' }], ["eur", { "locale": 'en-US', "style": 'currency', "currency": 'EUR' }], ["cad", { "locale": 'en-CA', "style": 'currency', "currency": 'CAD' }], ["jpy", { "locale": 'ja-JP', "style": 'currency', "currency": 'JPY' }], ["percent", { "locale": 'en-US', "style": 'percent' }], ["%", { "locale": 'en-US', "style": 'percent' }], ["comma", { "locale": 'en-US' }], [",", { "locale": 'en-US' }], ]); const $item = $(elem); const txt = $item.text().trim(); let val = parseFloat(txt); // Handle NaN, very small, or very large numbers if (isNaN(val) || Math.abs(val) < 1e-6 || Math.abs(val) > 1e21) { return $item.html(txt); // Return original text if it's not a valid number or is extreme } const fn = $item.attr("wfu-format"); const f = fs.get(fn); if (!f) return; let decimals = 0; if (txt.includes('.')) decimals = txt.split('.')[1].length; const settings = { style: f.style, currency: f.currency, minimumFractionDigits: decimals, maximumFractionDigits: decimals }; try { const formatter = new Intl.NumberFormat(f.locale, settings); const formattedValue = formatter.format(val); $item.html(formattedValue); } catch (error) { console.error('Error formatting field:', error); $item.html(txt); // Fallback to original text on error } } function handleFormatting() { $("*[wfu-format]").each(function() { formatField($(this)); }); } const debouncedHandleFormatting = debounce(handleFormatting, 100); document.addEventListener('touchstart', debouncedHandleFormatting); document.addEventListener('scroll', debouncedHandleFormatting); document.addEventListener('click', debouncedHandleFormatting); document.addEventListener('DOMContentLoaded', handleFormatting); /** * Credits * * Event listener implementation: Jordan Ryskamp * Huge thanks to the people over at Sygnal Technology Group. It wouldn't've been possible without you. Please check them out here: http://sygnal.com */