javascripttofixed

toFixed() method working isn't inside number() method in javascript?


What I want: after calculation result should be in 2 decimal format.

here's my code

let totalNetWeightLocal = 0;

totalNetWeightLocal = totalNetWeightLocal + Number((parseFloat(item.netWeight) * parseInt(item.quantity)).toFixed(2));

Problem: calculation is working but toFixed() isn't working. I'm getting results in more than 2 decimal values.

Can someone please help me?


Solution

  • 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));