Description |
The Val procedure is an older Delphi procedure that can convert a string NumberString into both integer and floating point variables.
The variable NumberVar must be appropriate to the number string. Specifically, an integer string value must be provided when NumberVar is an Integer type.
If the conversion succeeds, then ErrorCode is set to 0. Otherwise, it is set to the first character in NumberString that failed the conversion.
|
|
Notes |
Warning : it is safer to use the SysUtils conversion routines, such as StrToFloat where locale information is recognised. In particular, the character used for the decimal point.
|
|
Related commands |
Chr |
|
Convert an integer into a character |
IntToStr |
|
Convert an integer into a string |
StrToInt |
|
Convert an integer string into an Integer value |
|
|
|
Example code : Illustrate successful and unsuccessful floating point number string conversions |
// Full Unit code. // ----------------------------------------------------------- // You must store this code in a unit called Unit1 with a form // called Form1 that has an OnCreate event called FormCreate. unit Unit1; interface uses // The System unit does not need to be defined Forms, Dialogs; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} // Include form definitions procedure TForm1.FormCreate(Sender: TObject); var
numberString : string;
float : Extended;
errorPos : Integer;
begin // Set up a valid floating point number string
numberString := '12345.678';
// Convert it into a value
Val(numberString, float, errorPos);
// Display the string and converted value
if errorPos = 0
then ShowMessageFmt('Val(%s) = %12.3f',[numberString,float]);
// Val ignores the Decimal Separator - SysUtils converters don't
DecimalSeparator := '_';
numberString := '12345_678';
Val(numberString, float, errorPos);
if errorPos = 0
then ShowMessageFmt('Val(%s) = %12.3f',[numberString,float])
else ShowMessageFmt('Val(%s) failed at position %d',
[numberString, errorPos]);
end; end.
|
Hide full unit code |
Val(12345.678) = 12345.678
Val(12345_678) failed at position 6
|
|