How to convert variant value into integer?

user1556433 picture user1556433 · May 26, 2014 · Viewed 33.1k times · Source

Below is my code:

var
  i : integer;
  ...
  ...
if not VarIsNull(TcxLookupComboBox(Sender).EditValue) then
begin
  i := Integer(TcxLookupComboBox(Sender).EditValue);
end;

I can use VarToStr to convert variant into string but there is no VarToInt in Delphi for this. So, I have converted it like this Integer(TcxLookupComboBox(Sender).EditValue). Is this the right approach?

Answer

EchelonKnight picture EchelonKnight · May 26, 2014

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.