Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask to format int 1, 10, 100, to string "001", "010", "100"

Tags:

c#

How do I apply a mask to a string aiming to format the output text in the following fashion (at most 2 leading zeros):

int a = 1, b = 10, c = 100;
string aF = LeadingZeroFormat(a), bF = LeadingZeroFormat(b), cF = LeadingZeroFormat(c);
Console.Writeline("{0}, {1}, {2}", aF, bF, cF); // "001, 010, 100" 

What is the most elegant solution?

Thanks in advance.

like image 619
João Paulo Navarro Avatar asked May 15 '12 17:05

João Paulo Navarro


People also ask

How do I add zeros to a string?

Using ljust() to add trailing Zeros to the string This task can be performed using the simple inbuilt string function of ljust in which we just need to pass the number of zeros required in Python and the element to right pad, in this case being zero.

How do you add leading zeros to a string in C#?

The standard way to convert an int to a string with leading zeros in C# is using the String. PadLeft() method. It returns a new string of a specified length, with the string left padded with spaces or the specified character.


1 Answers

You can use Int32.ToString("000") to format an integer in this manner. For details, see Custom Numeric Format Strings and Int32.ToString:

string one = a.ToString("000"); // 001
string two = b.ToString("000"); // 010
like image 86
Reed Copsey Avatar answered Oct 28 '22 05:10

Reed Copsey