-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFormatNumbers.js
More file actions
94 lines (82 loc) · 3.25 KB
/
Copy pathFormatNumbers.js
File metadata and controls
94 lines (82 loc) · 3.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
class NumberFormatter {
constructor(_element) {
try {
this.element = _element;
this.locales = _element.getAttribute("wt-formatnumber-locales");
this.style = _element.getAttribute("wt-formatnumber-style");
this.currency = _element.getAttribute("wt-formatnumber-currency");
this.unit = _element.getAttribute("wt-formatnumber-unit");
this.value = _element.textContent;
if (!this.value) throw new Error("Number value is missing in the element.");
this.options = this.getFormatStyle(this.style, this.currency, this.unit);
if (!this.options) throw new Error("Invalid format options.");
this.formatNumber();
} catch (err) {
console.error(`Error initializing NumberFormatter: ${err.message}`);
}
}
getFormatStyle(_style, _currency, _unit) {
let _options = null;
if (_style) {
switch (_style) {
case 'currency':
if (!_currency) return null;
_options = {
style: _style,
currency: _currency
};
break;
case 'decimal':
case 'percent':
_options = { style: _style };
break;
case 'unit':
if (!_unit) return null;
_options = {
style: _style,
unit: _unit
};
break;
default:
return null;
}
return _options;
}
}
formatNumber() {
try {
const number = parseFloat(this.value.replace(/,/g, ''));
if (isNaN(number)) throw new Error("Invalid number value.");
const formattedNumber = new Intl.NumberFormat(this.locales, this.options).format(number);
if (!formattedNumber) throw new Error("Formatting failed.");
this.element.innerHTML = formattedNumber;
} catch (err) {
console.error(`Error formatting number: ${err.message}`);
}
}
}
const InitializeFormatNumbers = () => {
try {
window.webtricks = window.webtricks || [];
const numbersToFormat = document.querySelectorAll('[wt-formatnumber-element="number"]');
if (!numbersToFormat || numbersToFormat.length === 0) throw new Error("No elements found to format.");
numbersToFormat.forEach((numberContainer) => {
let instance = new NumberFormatter(numberContainer);
window.webtricks.push({'FormatNumber': instance});
});
} catch (err) {
console.error(`Format Number found an Error while initializing: ${err.message}`);
}
};
if (/complete|interactive|loaded/.test(document.readyState)) {
InitializeFormatNumbers();
} else {
window.addEventListener('DOMContentLoaded', InitializeFormatNumbers);
}
// Allow requiring this module in test environments without affecting browser usage
try {
if (typeof module !== 'undefined' && module.exports) {
module.exports = { NumberFormatter, InitializeFormatNumbers };
}
} catch {}