toFixed 在使用 reduce 方法 JS 之后
toFixed after using reduce method JS
我正在映射一个数组并将 50 个项目减少到 1 - 它们的总和。这 50 项是浮点精度数字。请帮忙,我不明白我应该把 toFixed(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)
}));
为了保持总和的准确性,请在对所有 value
求和后调用 toFixed
:
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);
至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);
我正在映射一个数组并将 50 个项目减少到 1 - 它们的总和。这 50 项是浮点精度数字。请帮忙,我不明白我应该把 toFixed(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)
}));
为了保持总和的准确性,请在对所有 value
求和后调用 toFixed
:
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);
至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);