Question on rounding off a sum

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;

:slight_smile:

You need Math.round. You’ll need to apply that to out before returning it.

Thanks for replying. Is there a way to have math.round round off two places after the decimal point? For example, the result I get for out is

$34376.49999999998

and I’d like the result to be

$34376.50

Thanks again! I think I’m getting close. I’ve modified the code to this:

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

Now I’m getting this value for out:

$34376.5

Please tell me: How can I get this value, instead?

$34376.50

Use toFixed :slight_smile:

U TH’ MAN! This worked:

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() …

OK. Someone at another forum suggested this:

		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 ; 			
		}

Seems to work. What do you think?

:slight_smile:

Yup looks fine :slight_smile:

It may work but have you validated the code?

The following validates:

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);
}