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
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
Filed under: C#, CodeProject, SQL
Tagged: C#, Database, internet, software, SQL 2005, SQL 2008, SQL Server, technology, Web