How to format a number with thousands separator (commas) in Pascal

1 Answer

0 votes
program FormatNumberWithCommas;

uses
  SysUtils; // IntToStr

function AddThousandsSeparator(number: Int64): string;
var
  numStr: string;
  i, j, len: Integer;
  resultStr: string;
begin
  // Convert the number to a string
  numStr := IntToStr(number);
  len := Length(numStr);
  resultStr := '';

  // Start inserting characters with commas
  j := 0; // Keeps track of how many digits have been added since the last comma
  for i := len downto 1 do
  begin
    resultStr := numStr[i] + resultStr; // Append digit at current position

    // Add a comma after every 3 digits (except for the first group)
    Inc(j);
    if (j mod 3 = 0) and (i > 1) then
      resultStr := ',' + resultStr;
  end;

  // Return the formatted result
  AddThousandsSeparator := resultStr;
end;

var
  number: Int64;
begin
  number := 9334567890128;

  WriteLn('Formatted number with commas: ', AddThousandsSeparator(number));
end.



(*
run:

Formatted number with commas: 9,334,567,890,128

*)

 



answered Mar 30, 2025 by avibootz

Related questions

1 answer 209 views
1 answer 113 views
1 answer 128 views
1 answer 117 views
1 answer 134 views
2 answers 205 views
1 answer 182 views
...