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
*)