412 Votes

Delphi: Add leading zeros to a number

Tip by Progger99 | Last update on 2020-10-28 | Created on 2012-08-14

Sometimes we want to display a number with leading zeros using Delphi or Lazarus, for example, in case that the numbers become double digits at some point and we directly want to start at 01, 02 and so on.

Fortunately there is a simple function which can do this for us:

str := Format('%.*d', [length, number]);
str := Format('%.*d', [3, 7]);
// str is '007'

The two required parameters are the number of places / leading zeros that we want to have (length) and the number as integer, we want to rewrite (number). The return value is a string.

In the second line you can see an example: When we call the function with the parameters 3 and 7, we get '007'.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.