Convert string with commas to float

前端 未结 9 2099
走了就别回头了
走了就别回头了 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条回答
  •  闹比i
    闹比i (楼主)
    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;
    

提交回复
热议问题