Transform into strings numbers containing semicolons

Asked

Viewed 708 times

2

I’m making an AJAX call and it’s returning me an array of objects as follows:

[
  {
    "area": "607,55"
  },
  {
    "area": "2.415,67"
  },
  {
    "area": "280,53"
  },
  {
    "area": "203,05"
  },
  {
    "area": "296,13"
  }
]

I would like to sum up all the areas, and I am doing it as follows using the .replace to change the comma:

let calculaArea = [];     
   result.forEach(function (result) {

         calculaArea.push(parseFloat(result.area.replace(/,/,'')));

       });
//console.log(calculaArea)
[
  60755,
  2.41567,
  28053,
  20305,
  29613
]
/////retornando array com numeros sem virgula/////

Next I’m adding the array of objects like this:

 let totalArea = calculaArea.reduce(function (a, b) {
                    return (a + b);
              });
///console.log(totalArea);
///
138728.41567000002
///

I’ve looked at several answers here but they only work with a few houses - example: 3.28 = 3,28.

Is there a more effective method for adding an array that contains semicolons, and holds 2 squares after the comma?

2 answers

4


According to the documentation, parseFloat considers that the point is the decimal separator. Therefore, it is not enough to remove the comma, as the second number becomes 2.41567, which is interpreted as 2.41567 and is not what we want.

So the way is to make one first replace to remove all points, and in the end we exchange the comma for a point:

let valores = [
  {
    "area": "607,55"
  },
  {
    "area": "2.415,67"
  },
  {
    "area": "280,53"
  },
  {
    "area": "203,05"
  },
  {
    "area": "296,13"
  }
];

let total = valores
    // transforma as strings da área em números
    .map(v => parseFloat(v.area.replace(/\./g, '').replace(',', '.')))
    // somar tudo e arredondar para duas casas decimais
    .reduce( (a, b) => a + b).toFixed(2);
console.log(total);

// ou, se quiser formatar o valor para usar pontos como separador de milhares e vírgulas como separador decimal
let totalNum = valores
    // transforma as strings da área em números
    .map(v => parseFloat(v.area.replace(/\./g, '').replace(',', '.')))
    // somar tudo e arredondar para duas casas decimais
    .reduce( (a, b) => a + b);
console.log(Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2}).format(totalNum));

The first replace uses \. to grab all points of the string (a flag g indicates that I want to replace all occurrences, since we can have values above 1 million can have more than one point). The second replace change the comma by a point, and at the end we have the string in the format that parseFloat understands.

Note that order is important. For example, if we have the string 1.234,56:

  • if I change the comma by a point first, it becomes 1.234.56, and if I remove the stitches, she flips 123456 (another hundred and twenty thousand, a value completely different from the original).
  • changing the point first, she turns 1234,56, and changing the comma for a point, it becomes 1234.56, that parseFloat interprets correctly as being "one thousand two hundred thirty-four, comma, fifty-six".

Then just add and use toFixed to round the result to two decimal places. Recalling that toFixed in fact round (2.345 rounded to two houses turns 2.35).

It is also worth remembering that toFixed returns a string. If you want the numeric value, take the return of reduce directly. Just don’t forget of that detail.


I also included a second option, to format the numerical value using the point as thousands separator and comma as decimal separator (plus always consider two decimal places). For more details, see documentation of NumberFormat.

  • friend @hkotsubo thank you so much also tested your code by changing some things and it worked perfectly, I wanted to know if it is possible with this result to add the "," comma to get real float in this example "3.802,93" thanks even!!

  • 1

    @luiz_vitorr I updated the answer with this option. And just to remind you how the site works: if one of the answers solved your problem, you can choose the one that best solved it and accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. Don’t forget that you can also vote in all the answers you found useful.

  • Thank you @hkotsubo I will be positivizing the reply and say that you were of great help by the tips

2

To get a javascript value, I turn into Number in that way.

 vp = Number(ValorTotalPedido.replace(/[R\$ \.]/g, '').replace(',', '.'));

You’d have to do something like this:

 calculaArea.push(Number(result.area.replace(/[R\$ \.]/g, '').replace(',', '.')));

Try this way. You will have to configure when passing the parameter.

  • thanks mariana your answer worked perfectly, I would ask right away how to do to put the 2 decimal places after the comma.. the other friend @hkotsubo answered right up.. then you 2 helped me a lot!!

  • 1

    @luiz_vitorr glad he helped you. We are the orders.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.