檢查字符串可否轉為數值型

来源:互联网 发布:python d3.js 编辑:程序博客网 时间:2024/05/05 14:29

1.用Delphi函数(建义)

function TryStrToFloat(const S: string; out Value: Extended): Boolean; overload;

function TryStrToFloat(const S: string; out Value: Double): Boolean; overload;
function TryStrToFloat(const S: string; out Value: Single): Boolean; overload;

function TryStrToFloat(const S: string; out Value: Extended; const FormatSettings: TFormatSettings): Boolean; overload;

function TryStrToFloat(const S: string; out Value: Double; const FormatSettings: TFormatSettings): Boolean; overload;
function TryStrToFloat(const S: string; out Value: Single; const FormatSettings: TFormatSettings): Boolean; overload;

 

2.自己写(不建义)

 檢查字符串可否轉為數值型

function IsNumStr(const S: String): Boolean;
var
  i, j: Integer;
  N, E: Integer;
  str1: String;
  s1, s2: String;
begin
  Result := False;
  str1 := Trim(S);
  if str1 = '' then
    Exit;
 
  Result := True;
  j := 0 ;
  s1 := '';
  s2 := '';
  for i := 1 to length(str1) do
  begin
    if not (str1[i] in ['0'..'9','.','-','+']) then
    begin
      Result := False;         //有非法字符
      Break;
    end;
    if str1[i] = '.' Then
    begin
      j := j + 1;
      if j >= 2 then
      begin
        Result := False;      //多於一個小數點'.'
        Break;
      end;
    end else
    begin
      if j < 1 then
        s1 := s1 + str1[i]     //存儲小數點前部份
      else
        s2 := s2 + str1[i];    //存儲小數點後部份
    end;
  end;
  if Result then
  begin
    Val(s1, N, E);            //參考StrToIntDef函數  
    if E <> 0 then
      Result := False;
  end;
  if Result And (s2 <> '') then
  begin
    Val(s2, N, E);
    if E <> 0 then
      Result := False;
  end;
end;

 

原创粉丝点击