猿问

使用reduce方法JS后的toFixed

我正在映射一个数组并将 50 个项目减少到 1 - 它们的总和。那 50 个项目是浮点精度数。请帮忙,我不明白我应该在该地图的哪个位置放置固定(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)

}));


动漫人物
浏览 185回答 1
1回答

慕娘9325324

为了保持总和准确,请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);仅在必要时输入小数点: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);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答