Author Topic: "groupModel" and "sum" floating point solution needed  (Read 82 times)

jplevene

  • Pro Ultimate
  • Full Member
  • *
  • Posts: 162
    • View Profile
"groupModel" and "sum" floating point solution needed
« on: August 26, 2025, 11:20:13 pm »
I am using:

Code: [Select]
groupModel: {
on: true,
header: false,
grandSummary: true,
agg: {"PRICE":"sum"}
},
summaryTitle:{sum:""},

The issue is that long decimals come from the server data which are converted to the correct currency (thus many decimal places needed) and rounded in the colModel.render which is all fine.  However when if I lets say get three PRICE values of 1.004, 1.004, 1.004, the total is 3.012 which rounds to 3.01 which is wrong as it should be 3.00 (1.00 + 1.00 + 1.00) as each row was rounded to 1.00.

How do I override the sum function, or add a custom sum function to round before adding each cell in the grouped column?  Also the cell needs to be rounded for Excel output due to the same issue in spreadsheet apps.

I've tried below but it doesn't work:

Code: [Select]
formulas: [
[
"sum",
function(rd)
{
return Math.round(rd.cellData * 100) / 100;
}
]
],
« Last Edit: August 27, 2025, 01:35:31 am by jplevene »

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6423
    • View Profile
Re: "groupModel" and "sum" floating point solution needed
« Reply #1 on: August 27, 2025, 09:51:24 am »
This is how you can define a custom aggregate to round the numbers before aggregating them.

Code: [Select]
pq.aggregate.sumRound = function(arr, col) {
   let rounded = arr.map(val => parseFloat(Number(val).toFixed(2)));
   return pq.aggregate.sum(rounded, col);
};

Now sumRound can be used in groupModel as

Code: [Select]
agg: {"PRICE":"sumRound"}