Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Pad Numbers with Leading and Ending Zeros

0.00/5 (No votes)
27 Jul 2016 1  
Pad numbers with leading and ending zeros

In a recent project, I got a list of integers something similar to the following:

1
12
123
1234
12345
….
123456789

and, I was asked to add zeros to the left or right of the list and make it as below:

List 1:
0000000001
0000000012
0000000123
…..
0123456789

List 2:
1000000000
1200000000
1230000000
….
1234567890

C# – PadLeft / PadRight

In C#, you can use PadLeft and PadRight functions to do this:

String.PadLeft Method (Int32, Char)

String.PadRight Method (Int32, Char)

int[] numbers = { 1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789 };

Console.WriteLine("List 1");
foreach (var i in numbers)
{
Console.WriteLine(i.ToString().PadLeft(10, '0'));
}

Console.WriteLine();
Console.WriteLine("List 2");
foreach (var i in numbers)
{
Console.WriteLine(i.ToString().PadRight(10, '0'));
}

PadLeft and PadRight

PadLeft and PadRight

SQL

Here comes the interesting part, I had to do this using SQL. In SQL, there are no inbuilt PadLeft or PadRight functions. So, I have used the LEFT and RIGHT SQL functions with a small hack.

CREATE TABLE [dbo].[NumberPadding](
[Number] [int] NOT NULL
) ON [PRIMARY]
GO;

INSERT INTO dbo.NumberPadding
VALUES (1), (12), (123), (1234), (12345), (123456), (1234567), (12345678), (123456789)
GO;

SELECT LEFT (CAST([Number] AS VARCHAR) + '0000000000', 10) FROM dbo.NumberPadding;

SELECT RIGHT ('0000000000' + CAST([Number] AS VARCHAR) , 10) FROM dbo.NumberPadding;

SQL - LEFT, RIGHT FUNCTIONS

SQL – LEFT, RIGHT FUNCTIONS

Filed under: C#, CodeProject, SQL
Tagged: C#, Database, internet, software, SQL 2005, SQL 2008, SQL Server, technology, Web

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here