简体   繁体   中英

Format a string like you would a numeric value

I have a string that I would like to format the same way I would a numeric value. Ex:

int num = 2;
string option = num.ToString("000");
Console.WriteLine(option);
//output
//002

But the only way I can think to format it is to parse it as an int, then apply the ToString("000") method to it.

string option = "2";
option = int.Parse(option).ToString("000");

Is there a better, more direct way to do this?

No, there is no built-in mechanism to "format" a string as if it were a number. Some options:

  • Use string functions ( Pad , Length , Substring ) to determine what characters should be added
  • Parse to a numeric type and use ToString with numeric formatting strings
  • Use a reqular expression to extract the digits and generate a new string

There's not one "right" answer. Each has risks and benefits in terms of safety (what if the string does not represent a valid integer?), readability, performance, etc.

Would this suit your requirement?

string x = "2";
string formattedX = x.PadLeft(3, '0');
Console.WriteLine(formattedX);  //prints 002

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM