Skip to content
Advertisement

Sum custom array of formatted numbers JS

I have a custom array of formatted numbers like the following:

[15.325,00  2.314,00  99.990,00  1.112.345,00]

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!

let a = ["15.325,00",  "2.314,00",  "99.990,00",  "1.112.345,00"];

function untitled(originalArrayString) { 

//turn array into array of numbers

    let arrayNum = originalArrayString.map(function(item) {
        return asNumber = Number.parseFloat(item.replace(/./g, '')
        .replace(/,/, '.'));
    })
    
//sum up numbers

    let answerAsNumber = arrayNum.reduce(function (accumulator,  number) { 
        return accumulator + number;
    });
    
//give answer in format

    function answerFormatted(answerAsNumber) { 
        let numberToString = String(answerAsNumber);
        let reverse = numberToString.split("").reverse().join("");
        let addPeriod = '';
        if (reverse.includes('.')) {
            let replaceDecimalWithComma = reverse.replace(/./, ',');
            addPeriod = replaceDecimalWithComma.replace(/(,)?d{3}B/g, '$&.');
        } else {
            addPeriod = reverse.replace(/d{3}B/g, '$&.');
            addPeriod = addPeriod.replace(/^/, '$&00,');
        }
        return reverted = addPeriod.split("").reverse().join("");
    }

    return answerFormatted(answerAsNumber);
    
}

console.log(untitled(a));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement