Convert string with commas to float

前端 未结 9 2159
走了就别回头了
走了就别回头了 2021-02-19 18:58

Is there a built-in Delphi function which would convert a string such as \'3,232.00\' to float? StrToFloat raises an exception because of the comma. Or is the only way to stri

9条回答
  •  野性不改
    2021-02-19 19:15

    Myfunction:

    function StrIsFloat2 (S: string;  out Res: Extended): Boolean;
    var
      I, PosDecimal: Integer;
      Ch: Char;
      STrunc: string;
      liDots, liComma, J: Byte;
    begin
      Result := False;
      if  S = ''
      then  Exit;
      liDots := 0;
      liComma := 0;
      for  I := 1 to Length(S)  do  begin
        Ch := S[I];
        if  Ch = FormatSettings.DecimalSeparator  then  begin
          Inc (liDots);
          if  liDots > 1  then  begin
            Exit;
          end;
        end
        else if  (Ch = '-') and (I > 1) then  begin
          Exit;
        end
        else if Ch = FormatSettings.ThousandSeparator then begin
          Inc (liComma);
        end
        else if not CharIsCipher(Ch) then  begin
          Exit;
        end;
      end;
      if liComma > 0 then begin
        PosDecimal := Pos (FormatSettings.DecimalSeparator, S);
        if PosDecimal = 0 then
          STrunc := S
        else
          STrunc := Copy (S, 1, PosDecimal-1);
        if STrunc[1] = '-' then
          Delete (S, 1, 1);
        if Length(STrunc) < ((liComma * 3) + 2) then
          Exit;
        J := 0;
        for I := Length(STrunc) downto 1 do begin
          Inc(J);
          if J mod 4 = 0 then
            if STrunc[I] <> FormatSettings.ThousandSeparator then
              Exit;
        end;
        S := ReplaceStr (S, FormatSettings.ThousandSeparator, '');
      end;
      try
        Res := StrToFloat (S);
        Result := True;
      except
        Result := False;
      end;
    end;
    

提交回复
热议问题