RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.Val Function

Converts a string to a numeric representation.

Pascal
procedure Val(S; var V; var Code: Integer);
C++
Val( S,  V, int Code);

In Delphi code, Val converts the string value S to its numeric representation, as if it were read from a text file with Read

S is a string-type expression; it must be a sequence of characters that form a signed real number.  

V is an integer-type or real-type variable. If V is an integer-type variable, S must form a whole number.  

Code is a variable of type Integer. 

If the string is invalid, the index of the offending character is stored in Code; otherwise, Code is set to zero. For a null-terminated string, the error position returned in Code is one larger than the actual zero-based index of the character in error.  

Delphi Examples: 

 

{
This example uses the System Val function to convert a string to
an integer.  Enter an integer in the text edit and then click the
button.  An error will occur if the value entered is not an integer.
}
procedure TForm1.Button1Click(Sender: TObject);
var
  I, Code: Integer;
  mystr: string;
begin
  { Get text from TEdit control }
  mystr := Edit1.Text;
  Val(mystr, I, Code);
  { Error during conversion to integer? }
  if Code <> 0 then
    MessageDlg('Error at position: ' + IntToStr(Code), mtWarning, [mbOk], 0, mbOk)
  else
    Canvas.TextOut(10, 10, 'Value = ' + IntToStr(I));
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!