使用reduce方法JS后toFixed

Vla*_*iuk 1 javascript arrays tofixed

我正在映射一个数组并将 50 个项目减少到 1 - 它们的总和。这 50 个项目是浮点精度数字。请帮忙,我不明白我应该在地图中的哪个位置放置到Fixed(2),以获得正确的summaryIncome属性,而不是这样的: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)
}));
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

为了保持总和准确,toFixed在对所有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);
Run Code Online (Sandbox Code Playgroud)

只把小数点如果需要的话

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);
Run Code Online (Sandbox Code Playgroud)