1 | 'use strict';
|
2 |
|
3 | module.exports = (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 (isNaN(value) || value === null) {
|
16 | return '';
|
17 | }
|
18 |
|
19 | value = Number(value);
|
20 | value = value.toFixed(~~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 |
|
34 | if (parseInt(parts[1], 10) === 0 && config.zeroDecimals !== undefined) {
|
35 | if (config.zeroDecimals === '' || config.zeroDecimals === null) {
|
36 |
|
37 | dec = '';
|
38 | } else {
|
39 |
|
40 | dec = config.decimalSeparator + config.zeroDecimals;
|
41 | }
|
42 | }
|
43 |
|
44 | const formattedValue =
|
45 | fnums.replace(/(?<num>\d)(?=(?:\d{3})+$)/g, '$1' + config.orderSeparator) + dec;
|
46 | return config.currencyPosition === 'before' ?
|
47 |
|
48 | curr + formattedValue :
|
49 |
|
50 | formattedValue + curr;
|
51 | };
|