Last post Dec 07, 2017 03:18 AM by Eric Du
Dec 06, 2017 10:14 PM|anooshiravan|LINK
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()?
Dec 06, 2017 10:24 PM|mgebhard|LINK
Dec 07, 2017 03:18 AM|Eric Du|LINK
According to your description and needs, i make a sample with two methods, please check:
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');