Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi isNumber

Tags:

Is there a method in Delphi to check if a string is a number without raising an exception?

its for int parsing.

and an exception will raise if one use the

try
  StrToInt(s);
except
  //exception handling
end;
like image 387
none Avatar asked Feb 03 '11 09:02

none


3 Answers

function TryStrToInt(const S: string; out Value: Integer): Boolean;

TryStrToInt converts the string S, which represents an integer-type number in either decimal or hexadecimal notation, into a number, which is assigned to Value. If S does not represent a valid number, TryStrToInt returns false; otherwise TryStrToInt returns true.

To accept decimal but not hexadecimal values in the input string, you may use code like this:

function TryDecimalStrToInt( const S: string; out Value: Integer): Boolean;
begin
   result := ( pos( '$', S ) = 0 ) and TryStrToInt( S, Value );
end;
like image 129
ba__friend Avatar answered Sep 28 '22 04:09

ba__friend


Try this function StrToIntDef()

From help

Converts a string that represents an integer (decimal or hex notation) to a number with error default.

Pascal

function StrToIntDef(const S: string; Default: Integer): Integer;

Edit

Just now checked the source of TryStrToInt() function in Delphi 2007. If Delphi 7 dont have this function you can write like this. Its just a polished code to da-soft answer

function TryStrToInt(const S: string; out Value: Integer): Boolean;
var
  E: Integer;
begin
  Val(S, Value, E);
  Result := E = 0;
end;
like image 38
Bharat Avatar answered Sep 28 '22 03:09

Bharat


var
  s: String;
  iValue, iCode: Integer;
...
val(s, iValue, iCode);
if iCode = 0 then
  ShowMessage('s has a number')
else
  ShowMessage('s has not a number');
like image 30
da-soft Avatar answered Sep 28 '22 04:09

da-soft