Hi. I have this JavaScript function that displays the sum of all the values of a column. Is there any way that I can modify the code to round the sum off to two decimal points?

function calculateFooterValues(stage){
if(stage && stage!=2)
return true;
var srQ = document.getElementById("sr_q");
srQ.innerHTML = "$"+sumColumn(6)
return true;
}
function sumColumn(ind){
var out = 0;
for(var i=0;i<mygrid.getRowsNum();i++){
out+= parseFloat(mygrid.cells2(i,ind).getValue())
}
return out;

function sumColumn(ind){
var out = 0;
for(var i=0;i<mygrid.getRowsNum();i++){
out+= parseFloat(mygrid.cells2(i,ind).getValue())
}
return out.toFixed(2) ;out;
}

[s]Note that .toFixed doesn’t round. So 1.059 will be returned as 1.05 (should be 1.06).

If you also want rounding you should probably do Math.round(number).toFixed(2)

:)[/s]

No, it does round. But please check a view inputs to see if you get what you want. The back of my mind is telling me there’s something odd about .toFixed() …

function sumColumn(ind){
var out = 0;
for(var i=0;i<mygrid.getRowsNum();i++){
out+= parseFloat(mygrid.cells2(i,ind).getValue())
}
out = "" + (Math.round(out * 100)) / 100 ;
if (out.indexOf(".") == out.length-2) { out +='0' ;
}
return out ;
}

function sumColumn(ind) {
var out = 0, i, mygrid;
for (i = 0; i < mygrid.getRowsNum(); i += 1) {
out += parseFloat(mygrid.cells2(i, ind).getValue());
}
out = "" + (Math.round(out * 100)) / 100;
if (out.indexOf(".") === out.length - 2) {
out += "0";
}
return out;
}

If in doubt combine round and tofixed (that way you take care of any rounding issues with tofixed).

function sumColumn(ind) {
var out = 0, i, mygrid;
for (i = 0; i < mygrid.getRowsNum(); i += 1) {
out += parseFloat(mygrid.cells2(i, ind).getValue());
}
return ((Math.round(out * 100)) / 100).toFixed(2);
}