22 Votes

Delphi/Lazarus: Convert Variant Variable to Integer

Question by Guest | Last update on 2022-12-02 | Created on 2014-12-31

I have a value of the type variant, but I need the integer variable type in my program to be able to calculate with the value.

In concrete terms, it is about a function that requires an integer number. As soon as I am passing the variant value to this function, the compiler creates an error message.

How is it possible to convert or translate a variant type value into an integer value?

ReplyPositiveNegativeDateVotes
3Best Answer3 Votes

The easiest way is to define an integer variable and to set this variable to the variant value:

var
  v: variant;
  i: integer;
begin
  v := 1;
  i := v;

  v := '1';
  i := v;
end;

This is even possible in the case that the variant value is actually a string.

If you nevertheless would like to check the type before, you can use the function VarType for that:

var
  v: variant;
  i: integer;
begin
  v := 1;
  
  if VarType(v) = varinteger then i := v;
end; 

VarType returns the type of the variant variable. Please note: There are also other number types instead of integers, so you can also check for "if (VarType(v) in [varinteger, varsmallint, varshortint, varbyte, varsingle, vardouble, varword, varlongword, varint64, varqword]) then begin..." or another list of types to ensure that you do not miss any type of number.
Last update on 2022-12-02 | Created on 2015-01-03

ReplyPositive Negative
33 Votes

Perhaps my way is a little bit inconvenient, but it should cover all possible cases (for example the case that the variant type is not an integer).

var
  v: variant;
  i: integer;
begin
  v := 1;
   
  i := StrToIntDef(Trim(VarToStr(v)), 0);
end; 

In this code, first, we are converting the variant variable into a string using VarToStr, then, we are cutting the whitespace (spaces, line breaks and so on) from the string using the trim function and after that we are using StrToIntDef to try to convert the string into an integer.

The second parameter of StrToIntDef (here 0) is the default value. This value is returned if it is not possible to convert the passed string into an integer.
2015-01-03 at 19:44

ReplyPositive Negative
Reply

Related Topics

Delphi: System-Wide HotKey

Tutorial | 1 Comment

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.