How to Add Leading Zeroes to a Number (Delphi Format)

Man using a laptop
Richard Saville

Different applications require specific values to conform to structural paradigms. For example, Social Security numbers are always nine digits long. Some reports require that numbers be displayed with a fixed amount of characters. Sequence numbers, for example, usually start with 1 and increment without end, so they're displayed with leading zeroes to present a visual appeal.

As a Delphi programmer, your approach to adding a number with leading zeroes depends on the specific use case for that value. You can simply opt to pad a display value, or you can convert a number to a string for storage in a database.

Display Padding Method

Use a straightforward function to change how your number displays. Use format to make the conversion by supplying a value for length (the total length of the final output) and the number you want to pad:

str := Format('%.*d,[length, number])

To pad the number 7 with two leading zeroes, plug those values into the code:

str := Format('%.*d,[3, 7]);

The result is 007 with the value returned as a string. 

Convert to String Method

Use a padding function to append leading zeroes (or any other character) any time you need it within your script. To convert values that are already integers, use:

function LeftPad(value:integer; length:integer=8; pad:char='0'): string; overload; 


   result := RightStr(StringOfChar(pad,length) + IntToStr(value), length ); 


If the value to be converted is already a string, use:

function LeftPad(value: string; length:integer=8; pad:char='0'): string; overload;


   result := RightStr(StringOfChar(pad,length) + value, length );


This approach works with Delphi 6 and later editions. Both of these code blocks default to a padding character of with a length of seven returned characters; those values may be modified to meet your needs.

When LeftPad is called, it returns values according to the specified paradigm. For example, if you set an integer value to 1234, calling LeftPad:

i:= 1234;
r := LeftPad(i);

will return a string value of 0001234.

mla apa chicago
Your Citation
Gajic, Zarko. "How to Add Leading Zeroes to a Number (Delphi Format)." ThoughtCo, Aug. 26, 2020, Gajic, Zarko. (2020, August 26). How to Add Leading Zeroes to a Number (Delphi Format). Retrieved from Gajic, Zarko. "How to Add Leading Zeroes to a Number (Delphi Format)." ThoughtCo. (accessed June 6, 2023).