Problem when computing average of a grid with empty numbers

Asked

Viewed 81 times

1

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

Imagens

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

2 answers

2


To function strtoint can launch an exception if the given string does not have a numeric format.

So instead of this:

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

Use this:

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

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

          if Cells[k, i] <> '' then
            sum := sum + strtoint(Cells[k, i]);

1

You can use the error handling system @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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.