UNPKG

1.2 kBJavaScriptView Raw
1'use strict';
2
3const geld = (value, options) => {
4 const config = {
5 currency: '€',
6 currencyPosition: 'after',
7 decimals: 2,
8 decimalSeparator: ',',
9 orderSeparator: '.',
10 zeroDecimals: '',
11 space: ' ',
12 ...options
13 };
14
15 if (!value || Number.isNaN(value) || Number.isNaN(Number(value))) {
16 return '';
17 }
18
19 value = Number(value);
20 value = value.toFixed(Math.trunc(config.decimals));
21
22 const parts = value.split('.');
23 const fnums = parts[0];
24 let dec = parts[1] ? config.decimalSeparator + parts[1] : '';
25
26 let curr = '';
27 if (config.currency) {
28 curr = config.currencyPosition === 'before' ?
29 config.currency + config.space :
30 config.space + config.currency;
31 }
32
33 // Do something with zero-valued decimals
34 if (Number.parseInt(parts[1], 10) === 0 && config.zeroDecimals !== undefined) {
35 dec = config.zeroDecimals === '' || config.zeroDecimals === null ? '' : config.decimalSeparator + config.zeroDecimals;
36 }
37
38 const formattedValue =
39 fnums.replace(/(?<num>\d)(?=(?:\d{3})+$)/g, '$1' + config.orderSeparator) + dec;
40 return config.currencyPosition === 'before' ?
41 // As in '$ 123'
42 curr + formattedValue :
43 // As in '123 €'
44 formattedValue + curr;
45};
46
47export default geld;