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

Match your approach to your use case

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

As a Delphi programmer, your approach to padding 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 within a database.

Display Padding

Use a straightforward function to change how your number displays.Use format to make your conversion by supplying a value for length (the total length of the final output) and the number you wish 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. 

Converting to String

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.

Delphi tips navigator:
» How to get the selected text from a Memo control
« How to clear the graphics in a TImage Delphi control