Afnan Ahmad
Afnan Ahmad

Reputation: 2542

How to pad an integer number with leading zeros?

I have strings that are being converted that need to be four characters long. The values are coming in as anywhere between 0 and 4 characters long. I need to pad the strings with zeros to make all IDs 4 characters long:

Example

Input number Need

1  => 0001
121 => 0121
0567 => 0567

So far I have tried:

int temCode = 0; 
DataTable dt = objSites.Get_Max_SiteCode();
if (dt.Rows.Count > 0)
{ 
     string siteCode = dt.Rows[0]["SiteCode"].ToString();
     string code = siteCode.Substring(siteCode.Length - 4);
     temCode = Convert.ToInt32(code) + 1;
     temCode.ToString().PadLeft(4, '0'); // same number is coming here without any pad left.
}

Upvotes: 2

Views: 6947

Answers (5)

Tariq
Tariq

Reputation: 2569

You can format you number to the length of your choice. Say code.ToSting("0000")

using System.IO;
using System;

class Program
{
    static void Main()
    {
       int i =30;
       String strI = i.ToString("0000");
       Console.WriteLine(strI);
    }
}

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391276

The problem is that the following:

  • .ToString()
  • .PadLeft(...)

all return a new string, they don't in any way modify the object you call the method on.

Please note that you have to place the result into a string. An integer value does not have any concept of padding, so the integer value 0010 is identical to the integer value 10.

So try this:

string value = temCode.ToString().PadLeft(4, '0');

or you can use this:

string value = temCode.ToString("d4");

or this:

string value = string.Format("{0:0000}", temCode);

Upvotes: 3

uriDium
uriDium

Reputation: 13420

When it comes to integer values 000001 = 1. So you won't be able to your integer with leading zeros as an numeric value. It will need to be stored as a string. So...

var foo = 1;
var formatted = foo.ToString().PadLeft(5, '0');

Upvotes: 0

WraithNath
WraithNath

Reputation: 18013

just use string.padleft.

eg:

int i = 100;
int length = 4;

string intString = i.ToString().PadLeft(length, '0');

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

You're not doing anything with the result of PadLeft - but you don't need to do that anyway. You can just specify the number of digits (and format) in the ToString call:

string result = temCode.ToString("d4");

Upvotes: 4

Related Questions