-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (38 loc) · 1.18 KB
/
index.js
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
const geld = (value, options) => {
const config = {
currency: '€',
currencyPosition: 'after',
decimals: 2,
decimalSeparator: ',',
orderSeparator: '.',
zeroDecimals: '',
space: ' ',
...options,
};
if (!value || Number.isNaN(value) || Number.isNaN(Number(value))) {
return '';
}
value = Number(value);
value = value.toFixed(Math.trunc(config.decimals));
const parts = value.split('.');
const fnums = parts[0];
let dec = parts[1] ? config.decimalSeparator + parts[1] : '';
let currency = '';
if (config.currency) {
currency = config.currencyPosition === 'before'
? config.currency + config.space
: config.space + config.currency;
}
// Do something with zero-valued decimals
if (Number.parseInt(parts[1], 10) === 0 && config.zeroDecimals !== undefined) {
dec = config.zeroDecimals === '' || config.zeroDecimals === null ? '' : config.decimalSeparator + config.zeroDecimals;
}
const formattedValue
= fnums.replaceAll(/(?<num>\d)(?=(?:\d{3})+$)/g, '$1' + config.orderSeparator) + dec;
return config.currencyPosition === 'before'
// As in '$ 123'
? currency + formattedValue
// As in '123 €'
: formattedValue + currency;
};
export default geld;