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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With