I have a custom array of formatted numbers like the following:
JavaScript
x
2
1
[15.325,00 2.314,00 99.990,00 1.112.345,00]
2
How can I sum them to 1.229.974,00
? Do I have to reformat them to integers (by some means), sum them and format the result? This format doesn’t look like a standard one.
Advertisement
Answer
Made an honest attempt. Looked short until it came to reformatting the answer. Any constructive criticism appreciated!
JavaScript
1
38
38
1
let a = ["15.325,00", "2.314,00", "99.990,00", "1.112.345,00"];
2
3
function untitled(originalArrayString) {
4
5
//turn array into array of numbers
6
7
let arrayNum = originalArrayString.map(function(item) {
8
return asNumber = Number.parseFloat(item.replace(/./g, '')
9
.replace(/,/, '.'));
10
})
11
12
//sum up numbers
13
14
let answerAsNumber = arrayNum.reduce(function (accumulator, number) {
15
return accumulator + number;
16
});
17
18
//give answer in format
19
20
function answerFormatted(answerAsNumber) {
21
let numberToString = String(answerAsNumber);
22
let reverse = numberToString.split("").reverse().join("");
23
let addPeriod = '';
24
if (reverse.includes('.')) {
25
let replaceDecimalWithComma = reverse.replace(/./, ',');
26
addPeriod = replaceDecimalWithComma.replace(/(,)?d{3}B/g, '$&.');
27
} else {
28
addPeriod = reverse.replace(/d{3}B/g, '$&.');
29
addPeriod = addPeriod.replace(/^/, '$&00,');
30
}
31
return reverted = addPeriod.split("").reverse().join("");
32
}
33
34
return answerFormatted(answerAsNumber);
35
36
}
37
38
console.log(untitled(a));