Reputation:
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?
Upvotes: 15
Views: 46528
Reputation: 1
I found a diferent soluction. If You are right that variant value is an integer value, You can use this:
//Using aggregate field in TClientDataSet
StrToInt(VarToStr(ClientDataSet.FieldByName('FieldName').AsVariant))
//Using a variant variable type
StrToInt(VarToStr(YourVariableName))
Is more easy
Upvotes: -1
Reputation: 51
AFAIK Delphi lacks of simple function like this below:
function VarToIntDef(const V: Variant; const ADefault: Integer = 0): Integer;
begin
if V = NULL then
Result := ADefault
else
Result := V;
end;
Upvotes: 0
Reputation: 331
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.
Upvotes: 15
Reputation: 1695
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.
Upvotes: 9