feat: Add currency support
Add support for formatting currency. This extends the library to become more useful
This commit is contained in:
parent
96fa327425
commit
f7f677ec38
|
|
@ -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 '<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 :
|
||||
// -------------
|
||||
|
|
@ -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();
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user