Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string to a 3 digit number

Instead of doing this, I want to make use of string.format() to accomplish the same result:

if (myString.Length < 3) {     myString =  "00" + 3; } 
like image 715
Alex Avatar asked Sep 24 '12 18:09

Alex


People also ask

Can you format a string?

The %s symbol represents a format specifier for Strings, similar to how %d represents a format specifier for decimal numbers. There are many format specifiers we can use. Here are some common ones: %c - Character.


2 Answers

If you're just formatting a number, you can just provide the proper custom numeric format to make it a 3 digit string directly:

myString = 3.ToString("000"); 

Or, alternatively, use the standard D format string:

myString = 3.ToString("D3"); 
like image 115
Reed Copsey Avatar answered Sep 21 '22 01:09

Reed Copsey


 string.Format("{0:000}", myString); 
like image 23
Haitham Salem Avatar answered Sep 20 '22 01:09

Haitham Salem