Name

Val Procedure

Syntax

procedure Val(const S: string; var Result; var Code; Integer);

Description

Val converts a string to a numeric value. The Result argument can be an integer, Int64, or floating-point variable. If the conversion is successful, Code is zero. Otherwise, the value of Code is the string position where Val first detected a format error. Val is not a real procedure.

Tips and Tricks

To convert a string to a floating-point number, use the string conversion functions in the SysUtils unit instead of Val. The problem is that Val does not heed the local settings for the decimal separator, making the procedure useless in an international setting.

Example

// Prompt the user for a number, and return the number that the
// user enters. If the user enters invalid input, show what
// the user mistyped and try again.
function GetNumber(const Prompt: string): Int64;
var
  S: string;
  Code: Integer;
begin
  repeat
    Write(Prompt);
    ReadLn(S);
    Val(S, Result, Code);
    if Code <> 0 then
    begin
      WriteLn(S);
      WriteLn('^':Code, ' invalid input');
    end;
  until Code = 0;
end;

See Also

Str Procedure

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.