Mike Torrettinni
Mike Torrettinni

Reputation: 1824

How to force StrToInt, StrToIntDef to ignore hex values?

I have variable that can hold either a string or an integer. So, I use If StrToIntDef(Value) > 0 to decide either I am processing strings or integers. But this fails, when the string starts with 'x' or 'X'. I assume because it thinks it's a hex number and converts it to integer:

procedure TForm1.Button1Click(Sender: TObject);
var
  Value:integer;
  Str:string;
begin

  Str:='string';
  Value:=StrToIntDef(Str,0); // Value = 0  OK

  Str:='xa';
  Value:=StrToIntDef(Str,0); // Value = 10 - NOT OK! Shuold be 0!

  Str:='XDBA';
  Value:=StrToIntDef(Str,0); // Value = 3514 - NOT OK! Shuold be 0!

end;

How can I make conversion function to ignore hex values?

Upvotes: 4

Views: 933

Answers (1)

David Heffernan
David Heffernan

Reputation: 613442

I think to be on the safe side you should validate that each character is a digit.

function StrToIntDefDecimal(const S: string; Default: Integer): Integer;
var
  C: Char;
begin
  for C in S do
    if ((C < '0') or (C > '9')) and (C <> '-') then
    begin
      Result := Default;
      exit;
    end;
  Result := StrToDef(S, Default);
end;

However, if you simply wish to detect whether or not the string is numeric, then you can do so like this:

function IsDecimalInteger(const S: string): Boolean;
var
  C: Char;
begin
  for C in S do
    if ((C < '0') or (C > '9')) and (C <> '-') then
    begin
      Result := False;
      exit;
    end;
  Result := True;
end;

Even this is imperfect because it will allow a value like '1-2'. But I am sure that you could modify the code to only accept '-' as the first character.

Note also that your existing test for a number, StrToIntDef(Value) > 0, will treat zero or negative numbers as strings. Is that really what you intend.

Upvotes: 3

Related Questions