Convert string with commas to float

前端 未结 9 2093
走了就别回头了
走了就别回头了 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:27

    I use a function which is able to handle the ',' and the '.' as decimalseparator...:

    function ConvertToFloat(aNr: String; aDefault:Integer): Extended;
    var
      sNr, s3R, sWhole, sCent:String;
      eRC:Extended;
    begin
      sNr:=ReplaceStr(sNr, ' ', '');
    
      if (Pos('.', sNr) > 0) or (Pos(',', sNr) > 0) then
      begin
        // Get 3rd character from right
        s3R:=LeftStr(RightStr(sNr, 3), 1);
        if s3R <> DecimalSeparator then
        begin
          if not IsNumber(s3R) then
          begin
            s3R := DecimalSeparator;
            sWhole := LeftSr(sNr, Length(sNr) - 3);
            sCent := (RightStr(sNr, 2);
            sNr := sWhole + DecimalSeparator + sCent;
          end
          else
            // there are no decimals... add ',00'
            sNr:=sNr + DecimalSeparator + '00';
        end;
        // DecimalSeparator is present; get rid of other symbols
        if (DecimalSeparator = '.') and (Pos(',', sNr) > 0) then sNr:=ReplaceStr(sNr, ',', '');
        if (DecimalSeparator = ',') and (Pos('.', sNr) > 0) then sNr:=ReplaceStr(sNr, '.', '');
      end;
    
      eRc := StrToFloat(sNr);
    end;
    

提交回复
热议问题