How to convert a string with either, or . as decimal/thousand separators into a float in Pascal

1 Answer

0 votes
program LocalizedStringToFloat;

uses
  SysUtils; // LastDelimiter // StrToFloat // Format

function ToFloat(const input: string): Double;
var
  str, temp: string;
  commaCount, dotCount, i: Integer;
  lastComma, lastDot: Integer;
begin
  str := input;
  commaCount := 0;
  dotCount := 0;

  // Count commas and dots
  for i := 1 to Length(str) do
    case str[i] of
      ',' : Inc(commaCount);
      '.' : Inc(dotCount);
    end;

  lastComma := LastDelimiter(',', str);
  lastDot := LastDelimiter('.', str);

  if (commaCount > 0) and (dotCount > 0) then
  begin
    if lastComma > lastDot then
    begin
      temp := '';
      for i := 1 to Length(str) do
        if str[i] <> '.' then
          if str[i] = ',' then
            temp := temp + '.'
          else
            temp := temp + str[i];
      str := temp;
    end
    else
    begin
      temp := '';
      for i := 1 to Length(str) do
        if str[i] <> ',' then
          temp := temp + str[i];
      str := temp;
    end;
  end
  else if commaCount > 0 then
  begin
    temp := '';
    for i := 1 to Length(str) do
      if str[i] = '.' then
        continue
      else if str[i] = ',' then
        temp := temp + '.'
      else
        temp := temp + str[i];
    str := temp;
  end
  else
  begin
    temp := '';
    for i := 1 to Length(str) do
      if str[i] <> ',' then
        temp := temp + str[i];
    str := temp;
  end;

  ToFloat := StrToFloat(str);
end;

begin
  WriteLn(Format('%.3f', [ToFloat('1,224,533.533')]));
  WriteLn(Format('%.3f', [ToFloat('1.224.533,533')]));
  WriteLn(Format('%.2f', [ToFloat('2.354,67')]));
  WriteLn(Format('%.2f', [ToFloat('2,354.67')]));
end.



(*
run:

1224533.533
1224533.533
2354.67
2354.67
 
*)

 



answered Jun 27, 2025 by avibootz
...