diff --git a/numberFormat.js b/numberFormat.js index dbde2c1..091734c 100644 --- a/numberFormat.js +++ b/numberFormat.js @@ -1,11 +1,11 @@ -// numberFormat.js +// numberFormat.js // --------------- // A simple tool to automagically format numbers for you using the Intl API // -// Usage: +// Usage: // ------ // Just wrap the numbers you want formatted in '' '' tags -// add the script in your document head wiht defer set +// add the script in your document head wiht defer set // COMING SOON : // ------------- @@ -36,21 +36,60 @@ // No, I will not add a LibreJS compatible comment // GNU won't support my choice of browser so I won't support their tool +// constant arrays to keep data validated +const currencyDisplays = ['symbol','narrowSymbol','code','name'] + function formatNumbers() { - + const numbers = document.getElementsByTagName("num"); const documentLanguage = document.documentElement.lang; - const formatter = Intl.NumberFormat(documentLanguage); - + var formatter = Intl.NumberFormat(documentLanguage); + for (let num of numbers) { var number = parseFloat(num.innerHTML); + if (isNaN(number)) { - console.error("[numberFormat.js] ERROR: cannot parse num element: " + num.innerHTML); + console.error("[numberFormat.js] ERROR: cannot parse num element: "); + console.error(num); continue; } + + if (num.attributes.currency) { + var f = _createCurrencyFormatter(num,documentLanguage); + if (f !== undefined) { + formatter = f; + } + } + var formatted = formatter.format(number); num.innerHTML = formatted; } } +function _createCurrencyFormatter(num,documentLanguage) { + var currency; + var currencyDisplay; + var currencyData = num.attributes.currency.value.split('-'); + currency = currencyData[0]; + if (currencyDisplays.includes(currencyData[1])) { + currencyDisplay = currencyData[1]; + } + else { + currencyDisplay = "symbol" + } + try { + formatter = Intl.NumberFormat(documentLanguage,{ + style: 'currency', + currency: currency, + currencyDisplay: currencyDisplay,}) + return formatter; + } catch (error) { + console.error("[numberFormat.js] ERROR: Failed to create NumberFormat"); + console.error(` - Check that ${currency} is a currency code`); + console.error(num) + } + return undefined; +} + +// ENTRY POINT formatNumbers();