:: My another contributions in Delphi

»Delphi3000.com
posting and uploading delphi articles
[currently as Top 66 uploader]


»Komunitas Delphi Indonesia
starting as a member

Thursday, November 23, 2006

:: Simple Way To Give Leading Zero In a Number

» String Format Function

Question/Problem/Abstract:

How can we put the leading zero in a Number with specifix n Max Digit place holder ??
Is there any Delphi built in function to do this job ??

Eg :
» if digit place holder is 5 => 00123
» if digit place holder is 3 => 012

Answer:
Actually, Delphi has supported to do this kind of job.
Yes, we can use function "Format" strings to do this
But we must do a little trick here to use it appropriately

Here is my example code:
********************************

function GiveLeadingZero(const aNumber, aMaxDigit: Integer): String;
var formatSpecifier: String;
begin
formatSpecifier := Format('%%.%dd', [aMaxDigit]);

// formatSpecifier will result like this: '%.5d' if aMaxDigit=5
Result := Format(formatSpecifier, [aNumber]);
end;

procedure TForm1.Button1Click(Sender: TObject);
var aNumber: Integer;
begin
if (TryStrToInt(Edit1.Text, aNumber)) then
Edit2.Text := GiveLeadingZero(aNumber, 5)
else
ShowMessage('Value in Edit1 is not a valid integer value');
end;

********************************

To use those code, simply juzt put two TEdit component on the Form with one button to execute the code



I think it solved the problem.

ps : the original code is posted @delphi3000.com [http://www.delphi3000.com/articles/article_4639.asp?SK=] by me either


0 comments: