Formatting values
Hi i have a int
example as 3
i need to format it as 003
. is the only way is convert to a st开发者_运维问答ring
and concat
and convert back ?
I guess this is what you want:
int n = 3;
string formatted = n.ToString("000");
Alternatively:
string formatted = String.Format("{0:000}", n);
More info here.
You can apply the .ToString("000");
method.
Debug.WriteLine(3.ToString("000"));
You can parse the resulting string value by using int.Parse
or int.TryParse
:
Debug.WriteLine(int.Parse("003"));
See Custom Numeric Format Strings
If it's an int object, the leading zeros will always be removed, regardless if you convert it to a string and back.
use the pad functionint i = 1;
i.ToString().PadLeft(3, '0');
精彩评论