feat: Add currency support

Add support for formatting currency.
This extends the library to become more useful
This commit is contained in:
Robert Morrison 2022-10-11 21:43:17 +01:00
parent 96fa327425
commit f7f677ec38
Signed by: robert
GPG Key ID: 73E012EB3F4EC696

View File

@ -1,11 +1,11 @@
// numberFormat.js // numberFormat.js
// --------------- // ---------------
// A simple tool to automagically format numbers for you using the Intl API // A simple tool to automagically format numbers for you using the Intl API
// //
// Usage: // Usage:
// ------ // ------
// Just wrap the numbers you want formatted in '<num>' '</num>' tags // Just wrap the numbers you want formatted in '<num>' '</num>' tags
// add the script in your document head wiht defer set // add the script in your document head wiht defer set
// COMING SOON : // COMING SOON :
// ------------- // -------------
@ -36,21 +36,60 @@
// No, I will not add a LibreJS compatible comment // No, I will not add a LibreJS compatible comment
// GNU won't support my choice of browser so I won't support their tool // 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() { function formatNumbers() {
const numbers = document.getElementsByTagName("num"); const numbers = document.getElementsByTagName("num");
const documentLanguage = document.documentElement.lang; const documentLanguage = document.documentElement.lang;
const formatter = Intl.NumberFormat(documentLanguage); var formatter = Intl.NumberFormat(documentLanguage);
for (let num of numbers) { for (let num of numbers) {
var number = parseFloat(num.innerHTML); var number = parseFloat(num.innerHTML);
if (isNaN(number)) { 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; continue;
} }
if (num.attributes.currency) {
var f = _createCurrencyFormatter(num,documentLanguage);
if (f !== undefined) {
formatter = f;
}
}
var formatted = formatter.format(number); var formatted = formatter.format(number);
num.innerHTML = formatted; 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(); formatNumbers();