Convert string with commas to float

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

    below is what i use. there might be more efficient ways, but this works for me. in short, no, i don't know of any built-in delphi function that will convert a string-float containing commas to a float

    {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      safeFloat
    
      Strips many bad characters from a string and returns it as a double.
    }
    function safeFloat(sStringFloat : AnsiString) : double;
    var
      dReturn : double;
    
    begin
      sStringFloat := stringReplace(sStringFloat, '%', '', [rfIgnoreCase, rfReplaceAll]);
      sStringFloat := stringReplace(sStringFloat, '$', '', [rfIgnoreCase, rfReplaceAll]);
      sStringFloat := stringReplace(sStringFloat, ' ', '', [rfIgnoreCase, rfReplaceAll]);
      sStringFloat := stringReplace(sStringFloat, ',', '', [rfIgnoreCase, rfReplaceAll]);
      try
        dReturn := strToFloat(sStringFloat);
      except
        dReturn := 0;
      end;
      result := dReturn;
    
    end;
    

提交回复
热议问题