DelphiBasics
StrToIntDef
Function
Convert a string into an Integer value with default SysUtils unit
 function StrToIntDef(const IntegerString string; Default Integer):Integer;
Description
The StrToIntDef function converts an Integer string, IntegerString such as '123' into an Integer value, with a Default if the conversion fails.
 
It supports +ve and -ve numbers, and hexadecimal numbers, as prefixed by $ or 0x.
Notes
No conversion errors are generated - bad conversions simply result in the Default being returned.
Related commands
IntegerThe basic Integer type
IntToStrConvert an integer into a string
StrToIntConvert an integer string into an Integer value
StrToInt64Convert an integer string into an Int64 value
StrToInt64DefConvert a string into an Int64 value with default
 Download this web site as a Windows program.




 
Example code : Converting decimal and hexadecimal numbers
var
  A, B, C, D, E, F : Integer;

begin
  A := 32;
  B := StrToIntDef('100', 0);    // '100' string converted to 100 integer
  C := StrToIntDef('  -12', 0);  // Leading blanks are ignored
  D := StrToIntDef('$1E', 0);    // Hexadecimal values start with a '$'
  E := StrToIntDef('-0x1E', 0);  // ... or with a '0x'
  F := A + B + C + D + E;    // Lets add up all these integers

  ShowMessage('A : '+IntToStr(A));
  ShowMessage('B : '+IntToStr(B));
  ShowMessage('C : '+IntToStr(C));
  ShowMessage('D : '+IntToStr(D));
  ShowMessage('E : '+IntToStr(E));
  ShowMessage('F : '+IntToStr(F));
end;
Show full unit code
  A : 32
  B : 100
  C : -12
  D : 30
  E : -30
  F : 120
 
Example code : Catching string to integer conversion errors
var
  A : Integer;

begin
  // No need to catch conversion errors
  A := StrToIntDef('100 ', 55);    // Trailing blanks are not supported
  ShowMessage('Value = '+IntToStr(A));

  A := StrToIntDef('$FG' , 66);    // 'G' is an invalid hexadecimal digit
  ShowMessage('Value = '+IntToStr(A));
end;
Show full unit code
  Value = 55
  Value = 66
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page