Skip to content

Commit f9cfb71

Browse files
committed
[Update] Added experimental functions
Functions added: - format Numbers
1 parent 0d61df4 commit f9cfb71

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

Dist/Functional/FormatNumbers.js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
* Number formating using Intl.NumberFormat.
3+
* Requirements:
4+
* Element with custom attribute fn-formatnumber="true"
5+
* A Style in the same element to format choosing between "Currency", "decimal", "percent", "unit"
6+
* In case of the element being "Currency" or "Unit" the sent "fn-formatnumber-currency" or "fn-formatnumber-unit" option
7+
* Optional: set locales for the formatting
8+
* list of units can be found here for now: https://tc39.es/proposal-unified-intl-numberformat/section6/locales-currencies-tz_proposed_out.html#sec-issanctionedsimpleunitidentifier
9+
* currency uses regular notation for them.
10+
*/
11+
12+
13+
let FormatNo = (element, locales, number, options) => {
14+
let final = Intl.NumberFormat(locales, options).format(number);
15+
if (!final) return;
16+
element.innerHTML = final;
17+
}
18+
const InitializeFormatNumbers = () => {
19+
let numbersToFormat = document.querySelectorAll('[wt-formatnumber-element="number"]');
20+
21+
if(!numbersToFormat || numbersToFormat.length === 0) return;
22+
23+
for(let numberContainer of numbersToFormat) {
24+
let locales = numberContainer.getAttribute("wt-formatnumber-locales");
25+
let style = numberContainer.getAttribute("wt-formatnumber-style");
26+
let currency = numberContainer.getAttribute("wt-formatnumber-currency");
27+
let unit = numberContainer.getAttribute("wt-formatnumber-unit");
28+
let options = null;
29+
30+
if (style) {
31+
switch (style) {
32+
case 'currency':
33+
if (!currency) return;
34+
options = {
35+
style: style,
36+
currency: currency
37+
}
38+
break;
39+
case 'decimal':
40+
options = {
41+
style: style
42+
};
43+
break;
44+
case 'percent':
45+
options = {
46+
style: style
47+
};
48+
break;
49+
case 'unit':
50+
options = {
51+
style: style,
52+
unit: unit
53+
};
54+
break;
55+
default:
56+
console.log(`undefined`);
57+
}
58+
}
59+
60+
let value = numberContainer.textContent
61+
if (!value) return;
62+
63+
try {
64+
FormatNo(numberContainer, locales, value, options);
65+
} catch (error) {
66+
numberContainer.innerHTML = `there was an error processing the format, ${error}`;
67+
}
68+
}
69+
}
70+
71+
window.addEventListener('DOMContentLoaded', InitializeFormatNumbers())

0 commit comments

Comments
 (0)