2

I am using ComponentOne Flexgrid for MVC and I am trying to sum a column.

I have the main grid (masterFlex) that contains the data. I then create a second single row grid (flex) that acts as the footer by mapping to masterFlex.

In trying to sum a numeric column:

for (vari=0; i < masterFlex.rows.length; i++)){
   sum += masterFlex.getCellData(i,0);
}
flex.setCellData(0,0,sum,false);

It is firing back NaN as the result. I did a typeof on the cells in the loop

sum = typeof(masterFlex.getCellData(i,0));
alert(sum);

Every result came back number, so why when I try and sum it do I get NaN?

blex
  • 22,377
  • 5
  • 35
  • 65
alemus
  • 254
  • 1
  • 2
  • 15
  • 2
    First, make sure you initiate `sum` to `0` before trying to add anything to it. Add a space in `vari=0`, remove the extra `)` after `i++))` and then, try to do `sum += +masterFlex.getCellData(i,0);` (notice the extra `+` sign) and tell us if it works. – blex Aug 14 '15 at 18:49
  • The extra ) after 1++ was just a typo, but the other additions worked. It also appears to work without the extra + sign before masterFlex. How do I mark the comment as the solution. – alemus Aug 14 '15 at 19:51
  • Great then. However, it might not work in all browsers (modern browsers tend to automatically treat Strings as Numbers when you do operations on them, but not older ones). The `+` sign is called "unary plus" and it [converts your String to a Number](http://stackoverflow.com/questions/5450076/whats-the-significant-use-of-unary-plus-and-minus-operators). It is an alternative to `parseInt` and `parseFloat`. You cannot mark a comment as a solution, I'll post it as an answer. – blex Aug 14 '15 at 19:55

1 Answers1

1
//First, make sure you initiate sum to 0 before trying to add anything to it.
var sum = 0;

for (var i = 0; i < masterFlex.rows.length; i++){
   // Then, just to make sure the value is treated as a Number, use the unary +
   sum += +masterFlex.getCellData(i,0);
}
blex
  • 22,377
  • 5
  • 35
  • 65