Wednesday 24 February 2010

CSharp: Pad Numbers with Leading Zeros

Question:
How to pad a number with leading Zeros?
How to get a 8 digits number block, where empty places are filled with zeros?
Formating a number with leading zeros.




Answer:
You can use a standard formating string for numerics in many ToString() or WriteLine() overloads.
The most common formating string are:
C for Currency
D for Decimal
G for General
E for Exponential
P for Percent
X for Hexa

Here is an example
int myInValue = 123;
string s = myIntValue.ToString("D8");
// s => "00000123"

No comments: