Mega Code Archive

 
Categories / Delphi / Examples
 

Simple Way To Give Leading Zero In a Number

Title: Simple Way To Give Leading Zero In a Number Question: 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 ?? Example: 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.