Format Numbers to Fix Length in C#

December 03, 2012 // In: C#

You have noticed that Invoices, Bill numbers mostly have fixed length, and it can be achieved by formatting string to fix length by adding zeros to the left of the string or number.

If you are generating invoices or any other report that may include Invoice number, bill number or any other identification that should have fix length. You may need to Format numbers or string to fix length by padding zeros to the left of the string or integer.

You can develop a simple function to Formatting string to fix length in c#. You can convert this c# function to VB with little modifications.

Following is the function that you can use for string formatting in c# for fix length by padding zeros to the left

Method 1

Method 2

Function is passing two parameter (str, digits). First parameter (str) for the actual string or number that you want to fix with zeros and Second is the fix length that you want your string or number should have.

Here is the example Code of a console application

The Output of the Example is

Calculate md5 Hash in C#
Introduction to C# (C Sharp) Class
  • Memoria

    This is useless when you can already use the built-in PadLeft method from any string.

    • Built-in Method Added, Thanks for suggestion.