1 回答
TA贡献1783条经验 获得超4个赞
为了保持总和准确,请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);
添加回答
举报