How to make StrToInt, StrToIntDef ignore hexadecimal values?

I have a variable that can contain a string or an integer. Therefore, I use If StrToIntDef(Value) > 0to decide if I am processing strings or integers. But this fails when the line starts with "x" or "X". I assume that it counts the hexadecimal number and converts it to an 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 to make conversion function ignore hexadecimal values?

+4
source share
1 answer

I think that from the reliable side you should confirm that each character is a number.

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;

, , , :

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;

, , '1-2'. , , '-' .

, StrToIntDef(Value) > 0 . , .

+3

Source: https://habr.com/ru/post/1673712/


All Articles