Format string to a 3 digit number

C#StringNumbersFormat

C# Problem Overview


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

if (myString.Length < 3)
{
    myString =  "00" + 3;
}

C# Solutions


Solution 1 - C#

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");

Solution 2 - C#

 string.Format("{0:000}", myString);

Solution 3 - C#

It's called Padding:

myString.PadLeft(3, '0')

Solution 4 - C#

This is how it's done using string interpolation C# 7

$"{myString:000}"

Solution 5 - C#

(Can't comment yet with enough reputation , let me add a sidenote)

Just in case your output need to be fixed length of 3-digit , i.e. for number run up to 1000 or more (reserved fixed length), don't forget to add mod 1000 on it .

yourNumber=1001;
yourString= yourNumber.ToString("D3");        // "1001" 
yourString= (yourNumber%1000).ToString("D3"); // "001" truncated to 3-digit as expected

Trail sample on Fiddler https://dotnetfiddle.net/qLrePt

Solution 6 - C#

This is a short hand string format Interpolation:

$"{value:D3}"

Solution 7 - C#

"How to: Pad a Number with Leading Zeros" http://msdn.microsoft.com/en-us/library/dd260048.aspx

Solution 8 - C#

Does it have to be String.Format?

This looks like a job for String.Padleft

myString=myString.PadLeft(3, '0');

Or, if you are converting direct from an int:

myInt.toString("D3");

Solution 9 - C#

You can also do : string.Format("{0:D3}, 3);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - C#Reed CopseyView Answer on Stackoverflow
Solution 2 - C#Haitham SalemView Answer on Stackoverflow
Solution 3 - C#PinnyMView Answer on Stackoverflow
Solution 4 - C#AliView Answer on Stackoverflow
Solution 5 - C#SxcView Answer on Stackoverflow
Solution 6 - C#Maytham FahmiView Answer on Stackoverflow
Solution 7 - C#user287107View Answer on Stackoverflow
Solution 8 - C#SconibulusView Answer on Stackoverflow
Solution 9 - C#sstassinView Answer on Stackoverflow