Answered by:
string formatting

Question
-
User1024191908 posted
I have a method that returns a string which represents some time in milliseconds.
I want to detect if it is less than 10 then add two zeros to its left and if it is more than 10 then add one zero.
I can easily do it with an If...Else but I wonder if there is any way to do such things with methods like String.Format()?
thanks
Wednesday, December 6, 2017 10:14 PM
Answers
-
User475983607 posted
Use the string.PadLeft() function.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, December 6, 2017 10:24 PM -
User-1838255255 posted
Hi anooshiravan,
According to your description and needs, i make a sample with two methods, please check:
Sample Code:
protected void Page_Load(object sender, EventArgs e) { string value = "5"; // Method one string format1 = "D" + (value.Length + 1).ToString(); string format2 = "D" + (value.Length + 2).ToString(); var newvalue1 = Convert.ToUInt32(value).ToString(format1); var newvalue2 = Convert.ToUInt32(value).ToString(format2); string result1 = Convert.ToInt32(value) < 10 ? newvalue2 : newvalue1; Response.Write(result1 + "</br>"); // Method two string result2 = Convert.ToInt32(value) < 10 ? value.PadLeft(value.Length + 2, '0') : value.PadLeft(value.Length + 1, '0'); Response.Write(result2); }
Best Regards,
Eric Du
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, December 7, 2017 3:18 AM
All replies
-
User475983607 posted
Use the string.PadLeft() function.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, December 6, 2017 10:24 PM -
User-1838255255 posted
Hi anooshiravan,
According to your description and needs, i make a sample with two methods, please check:
Sample Code:
protected void Page_Load(object sender, EventArgs e) { string value = "5"; // Method one string format1 = "D" + (value.Length + 1).ToString(); string format2 = "D" + (value.Length + 2).ToString(); var newvalue1 = Convert.ToUInt32(value).ToString(format1); var newvalue2 = Convert.ToUInt32(value).ToString(format2); string result1 = Convert.ToInt32(value) < 10 ? newvalue2 : newvalue1; Response.Write(result1 + "</br>"); // Method two string result2 = Convert.ToInt32(value) < 10 ? value.PadLeft(value.Length + 2, '0') : value.PadLeft(value.Length + 1, '0'); Response.Write(result2); }
Best Regards,
Eric Du
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, December 7, 2017 3:18 AM