Search code examples
delphitstringgrid

Percentage mask on some cells of the TStringGrid


I have a TStringGrid where I will type in each column a value and I need a mask for the value to appear as a percentage, I am a beginner with Delphi but I saw that there is an OnGetEditMask method but I do not know how to create a mask for the percentage ... then I go manipulate this value into a variable of type Double. Example I enter 5,4 and with the mask gets 5,4%

Then how do I get the list data into Double?


Solution

  • You are correctly assigning the Value parameter in the OnGetEditMask event (assuming your regional settings use decimal comma and not decimal point), repeated here for completeness:

    procedure TForm1.StringGrid1GetEditMask(Sender: TObject; ACol, ARow: Integer;
      var Value: string);
    begin
      if (ACol = 0) or (ACol = 1) then
        Value := '99,9%';
    end;
    

    Then, to convert the string content of the cell to a double, you need to remove the percent sign from the string before you pass it to, e.g. StrToFloatDef():

    For example:

    procedure TForm1.Button1Click(Sender: TObject);
    var
      s: string;
      d: double;
      b: boolean;
    begin
      b := False;
      s := StringGrid1.Cells[1, 1];
      if s <> '' then
      begin
        if s[Length(s)] = '%' then
        begin
          s := copy(s, 1, Length(s)-1);
          b := true;
        end;
        d := StrToFloatDef(s, 0.0);
        if b then d := d / 100;
      end;
      ShowMessage(FloatToStr(d));
    end;