Convert string with commas to float

前端 未结 9 2098
走了就别回头了
走了就别回头了 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:32
    function StrToFloat_Universal( pText : string ): Extended;
    const
       EUROPEAN_ST = ',';
       AMERICAN_ST = '.';
    var
      lformatSettings : TFormatSettings;
      lFinalValue     : string;
      lAmStDecimalPos : integer;
      lIndx           : Byte;
      lIsAmerican     : Boolean;
      lIsEuropean     : Boolean;
    
    begin
      lIsAmerican := False;
      lIsEuropean := False;
      for lIndx := Length( pText ) - 1 downto 0 do
      begin
        if ( pText[ lIndx ] = AMERICAN_ST ) then
        begin
          lIsAmerican := True;
          pText := StringReplace( pText, ',', '', [ rfIgnoreCase, rfReplaceAll ]);  //get rid of thousand incidental separators
          Break;
        end;
        if ( pText[ lIndx ] = EUROPEAN_ST ) then
        begin
          lIsEuropean := True;
          pText := StringReplace( pText, '.', '', [ rfIgnoreCase, rfReplaceAll ]);  //get rid of thousand incidental separators
          Break;
        end;
      end;
      GetLocaleFormatSettings( LOCALE_SYSTEM_DEFAULT, lformatSettings );
      if ( lformatSettings.DecimalSeparator = EUROPEAN_ST ) then
      begin
        if lIsAmerican then
        begin
          lFinalValue := StringReplace( pText, '.', ',', [ rfIgnoreCase, rfReplaceAll ] );
        end;
      end;
      if ( lformatSettings.DecimalSeparator = AMERICAN_ST ) then
      begin
        if lIsEuropean then
        begin
          lFinalValue := StringReplace( pText, ',', '.', [ rfIgnoreCase, rfReplaceAll ] );
        end;
      end;
      pText  := lFinalValue;
      Result := StrToFloat( pText, lformatSettings );
    end;
    
    0 讨论(0)
  • 2021-02-19 19:32

    using lemda Expression to convert string comma seprated to float array

    public static float[] ToFloatArrayUsingLemda()
        {
            string pcords="200.812, 551.154, 232.145, 482.318, 272.497, 511.752";
            float[] spiltfloat = new float[pcords.Split(',').Length];
    
            string[] str = pcords.Split(',').Select(x => x.Trim()).ToArray();
    
            spiltfloat = Array.ConvertAll(str, float.Parse);
            return spiltfloat;
        }
    
    0 讨论(0)
  • 2021-02-19 19:38

    Do you exactly know, that '.' is decimal separator and ',' is thousand separator (always)? If so, then you should fill the TFormatSettings record and pass it to StrToFloat.

    FillChar(FS, SizeOf(FS), 0);
    ... // filling other fields
    FS.ThousandSeparator := ',';
    FS.DecimalSeparator := '.';
    V := StrToFloat(S, FS);
    
    0 讨论(0)
提交回复
热议问题