How to convert variant value into integer?

This might help:

function VarToInt(const AVariant: Variant): integer;
begin
  Result := StrToIntDef(Trim(VarToStr(AVariant)), 0);
end;

procedure TForm1.BitBtn3Click(Sender: TObject);
begin
  ShowMessage(IntToStr(VarToInt(NULL)));
  ShowMessage(IntToStr(VarToInt(' 124   ')));
  ShowMessage(IntToStr(VarToInt(13.87)));
  ShowMessage(IntToStr(VarToInt('Edijs')));
end;

Results are: 0, 124, 0 and 0. You can make it to work with floats tho.


Have a look at this: http://docwiki.embarcadero.com/RADStudio/Rio/en/Variant_Types

Specifically check the Variant Type Conversions section.

You should be able to assign is directly using implicit type casting. As in Delphi just handles it for you.

As an example:

var
  theVar: Variant;
  theInt: integer;
begin

  theVar := '123';
  theInt := theVar;
  showmessage(IntToStr(theint));
end;

This works without issue.

To ensure that your data is an integer and that it is safe to do at runtime (as in to make use that you didn't have a string value in the variant, which would result in a runtime error) then have a look at the Val function: http://docwiki.embarcadero.com/Libraries/Rio/en/System.Val

Hope this helps.