Problem when calculating average of a grid with empty numbers

1

I have a StringGrid1 that fill in the data and from that I calculate the total and average. In figure 1, it shows working correctly. However I may not want to put a number in one of the cells, which causes the image error 2.

The code I'm using:

procedure TForm2.Calcular(Sender: TObject);
begin
  SaveStringGrid(StringGrid1, 'c:\temp.txt');
end;


procedure SaveStringGrid(StringGrid: TStringGrid; const FileName: TFileName);
var
  f:    TextFile;
  i, k, sum: Integer;
  med: EXTENDED;
begin
  with StringGrid do
  begin
    for i := 1 to RowCount-1 do
    begin
      sum := 0;
      med := 0;

      for k := 1 to ColCount-3 do
        begin
          sum :=sum + strtoint(Cells [k, i]);
          med := sum / k;
          Cells [ColCount -2, i] := inttostr(sum);
          Cells [ColCount -1, i] := FloatToStr(med);
        end;
    end;
  en
    
asked by anonymous 31.01.2018 / 01:07

2 answers

2

The strtoint function can throw an exception if the given string does not have a format number.

So, instead:

          sum :=sum + strtoint(Cells [k, i]);

Use this:

          try
            sum := sum + strtoint(Cells[k, i]);
          on Exception : EConvertError do
            // Ignora a exceção
          end;

This will make him ignore any cells with non-numeric formats. If you want to ignore only those that are blank, then simply use this:

          if Cells[k, i] <> '' then
            sum := sum + strtoint(Cells[k, i]);
    
31.01.2018 / 01:50
1

You can use the error handling system that @Victor Stafusa suggested, or you can use a variation of the function you already use, which is StrToInt :

instead of:

sum :=sum + strtoint(Cells [k, i]);

use:

sum :=sum + StrToIntDef(Cells [k, i], 0);

StrToIntDef tries to convert and assumes the value that was set after the comma.

There are others like StrToFloatDef , StrToDateTimeDef etc. See more details on System.SysUtils

    
31.01.2018 / 11:15