javascriptarraystofixed

toFixed after using reduce method JS


I`m maping through an array and reducing 50 items to 1 - their sum. That 50 items are float precision numbers. Please help, I don`t understand where in that map I should put toFixed(2), to get proper summaryIncome property instead something like this: 39990,89999999999913.

var data = [
  {id: 1, incomes: [{value:1}, {value: 2}]}, 
  {id: 2, incomes: [{value:2}, {value: 3}]}],
  ...
]

var summary = data.map(item => ({
  ...item,
  summaryIncome: item.incomes.reduce((acc, income) =>
    acc += income.value, 0)
}));

Solution

  • To keep the sum accurate, call toFixed after summing up all the values:

    var data = [
      {id: 1, incomes: [{value: 0.1}, {value: 0.2}]}, 
      {id: 2, incomes: [{value:2}, {value: 3}]},
    ]
    
    var summary = data.map(item => ({
      ...item,
      summaryIncome: item.incomes.reduce((acc, income) => acc + income.value, 0).toFixed(2)
    }));
    console.log(summary);

    To only put decimal points if necessary:

    var data = [
      {id: 1, incomes: [{value: 0.1}, {value: 0.2}]}, 
      {id: 2, incomes: [{value:2}, {value: 3}]},
    ]
    
    var summary = data.map(item => ({
      ...item,
      summaryIncome: (() => {
        const trueSum = item.incomes.reduce((acc, income) => acc + income.value, 0);
        return Number.isInteger(trueSum) ? String(trueSum) : trueSum.toFixed(2);
      })()
    }));
    console.log(summary);