The problem with your code is, that the .toFixed(2)
is at the wrong position
What your code does is something like
const fullWeight = parseFloat(item.netWeight) * parseInt(item.quantity)
totalNetWeightLocal = totalNetWeightLocal + fullWeight.toFixed(2));
Which means, you add two strings together like 0 + '10.24'
which will be 010.24
. What you need to do is:
// you don’t need Number() here:
const itemWeight = parseFloat(item.netWeight) * parseInt(item.quantity)
totalNetWeightLocal += itemWeight;
totalNetWeightLocal.toFixed(2);
Considering, you might have a list of items you can write a functions as follows:
const items = [
{ netWeight: '4.53', quantity: '3' },
{ netWeight: '20.33', quantity: '10' }
];
const getTotalNetWeightLoal = items => {
const totalNetWeightLocal = items.reduce(
(weight, { netWeight, quantity }) =>
weight + parseFloat(netWeight) * parseInt(quantity),
0
);
return totalNetWeightLocal.toFixed(2);
};
console.log(getTotalNetWeightLoal(items));