Issue
I have simple function of calculating the sum of numbers and strings in columns in a table. The sum works well and gives me correct results. The issue is that whenever I try to divide the total sum of each column with 100 I end up with wrong values
Scenario A
I have a sum of 969.35
in column A, whenever I divide the value with 100
I expect to get 9.69
but I end up with 0.51
. Am not sure why this is being calculated as so.
This is my implementation of getting the sum
getSum(columnNumber) {
let sum = 0;
const columnNumberToPropertyMap = [
"id",
"teamNumber",
"rural",
"completed",
"entirehouseholdabsent",
"postponed",
"refused",
"vacant",
"dwelling"
];
const property = columnNumberToPropertyMap[columnNumber];
return this.rural.reduce((acc, curr) => {
//const adder = Number(curr[property]) || 0;
const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
sum = acc + adder
return sum;
}, 0).toFixed(2);
}
the above code works well as I can get the sum of each coiumn.
How I am trying to get the percentage
getSum(columnNumber) {
let sum = 0;
let percentage = 0;
const columnNumberToPropertyMap = [
"id",
"teamNumber",
"rural",
"completed",
"entirehouseholdabsent",
"postponed",
"refused",
"vacant",
"dwelling"
];
const property = columnNumberToPropertyMap[columnNumber];
return this.rural.reduce((acc, curr) => {
//const adder = Number(curr[property]) || 0;
const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
sum = acc + adder
percentage = (sum)/100;
return percentage ;
}, 0).toFixed(2);
}
What am I doing wrong?
Solution
Do this it will be fine. You are dividing each time which is causing issue.
Percentage should be outside of reduce loop.
(this.rural.reduce((acc, curr) => {
//const adder = Number(curr[property]) || 0;
const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
sum = acc + adder
percentage = sum;
return percentage ;
}, 0) / 100).toFixed(2);