0

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.

Naffets
  • 151
  • 3
  • 4
  • 13
  • 1
    array elements are probably strings, aren't them? – briosheje Sep 04 '20 at 14:26
  • they are stored as strings, yes – Naffets Sep 04 '20 at 14:30
  • Does https://stackoverflow.com/questions/29255843/is-there-a-way-to-reverse-the-formatting-by-intl-numberformat-in-javascript answer your question ? – 36ve Sep 04 '20 at 14:33
  • You should convert those strings to numbers, then sum them. Example: `const res = arr.reduce((acc, next) => { return acc + Number.parseFloat(next.replace(/\./g, '').replace(/\,/g, '.')); }, 0);` – briosheje Sep 04 '20 at 14:35

3 Answers3

1

You could remove unwanted characters, sum the values and apply the format.

const
    format = value => value
        .toString()
        .padStart(3, 0)
        .replace(/.{1,3}(?=(.{3})*..$)/g, (p, _, o, s) => p + (o + 5 === s.length ? ',' : '.'));

var data = ['15.325,00', '2.314,00', '99.990,00', '1.112.345,00'],
    sum = format(data.reduce((s, v) => s + +v.replace(/\D/g, ''), 0));

console.log(sum);
console.log(format(0)); // to get a minimum string length
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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));
tonitone120
  • 1,920
  • 3
  • 8
  • 25
0

This does the work, but doesn't add "00" fraction if integer.

function formattedToFloat(str, decimal=".", thousands=",") {
  return parseFloat(str.split(decimal).map(item=>item.split(thousands).join("")).join(decimal));
}

function floatToFormatted(flt, decimal=".", thousands=",") {
  return flt.toString().split(decimal).map((cv,i)=>{
    if(i) return cv;
    else {
      var cva=cv.split("");
      var sep=cva.length%3;
      var ret=[];
      do {
        var dig=cva.pop();
        ret.unshift(dig);
        if(cva.length%3==sep && cva.length) ret.unshift(thousands);
      } while (cva.length);
      return ret.join("");
    }
  }).join(decimal);
}

var arr=["15.325,00", "2.314,00", "99.990,00",  "1.112.345,00"];

console.log(floatToFormatted(arr.reduce((acc, cv)=>acc+formattedToFloat(cv, ",", "."),0), ",", "."));
iAmOren
  • 2,760
  • 2
  • 11
  • 23
  • @customcommander, I did and it worked, tried to make it look better and killed it - regressed to previous = works now. Does it work for you? – iAmOren Sep 04 '20 at 15:22