Problems with Sums JS

0

The problem that arises for sure is very simple, what I present in the code is something done with Firebase that returns all the data of my DB and places them in a table.

At the end in "Total" I assigned the first "amount" to then add the next and enter "cellTotal" , but instead of adding me concatenated as if all amount was a string , being that from DB comes to me as a whole and "Total" I initialize it as a int .

I would appreciate the help.

Edit:

At the time I was concatenated because I put cellTotal += nuevoServicio.monto , but in the following way it only shows me the last object of the base total = total + nuevoServicio.monto; cellTotal.innerText = total; if I have added the requested.

//Mantengo actualizada la tabla de servicios
dbSer.on('child_added', snap => {
var nuevoServicio = snap.val();

let cellTotal= document.querySelector('#totalImpuesto');
let total = 0;
let tb = document.querySelector('#tb-body');

let tr = document.createElement('tr');
let td1 = document.createElement('td');
let td2 = document.createElement('td');

let text1 = document.createTextNode(nuevoServicio.servicio);
let text2 = document.createTextNode(nuevoServicio.monto);

td1.appendChild(text1);
td2.appendChild(text2);

tr.appendChild(td1);
tr.appendChild(td2)

tb.appendChild(tr);

total = total + nuevoServicio.monto;

cellTotal.innerText = total;
})

The result of a console.log(JSON.stringify(nuevoServicio)) returns me:

{"monto":3000,"servicio":"Casa"}
{"monto":200,"servicio":"Gas"}
{"monto":350,"servicio":"Luz"}

Which is clearly an INT.

And when adding:

total = total + parseInt(nuevoServicio.monto, 10); cellTotal.innerText = total

It returns 350 which is the last object of the base.

    
asked by Alfacoy 09.01.2018 в 00:00
source

1 answer

2

The only reason why the values would be concatenated (instead of being added) is because nuevoServicio.monto has to be a string .

Solution:

You could use parseInt ( without decimals ) or parseFloat ( with decimals >)

Example:

total = total + parseInt(nuevoServicio.monto, 10);

Update

The reason you get only the last value is because every time the child_added event is executed, the variable total is initialized to 0 .

Solution:

You should initialize the total variable outside the function.

Example:

let total = 0;
dbSer.on('child_added', snap => {
  var nuevoServicio = snap.val();

  let cellTotal= document.querySelector('#totalImpuesto');
  //... resto del código 
    
answered by 09.01.2018 / 00:20
source