'How to change 1 to 00001?
I want to have numbers with a fixed digit count.
example: 00001, 00198, 48484
I can do like this:
string value;
if (number < 10)
{
value = "0000" + number.ToString();
}
else if (number < 100)
{
value = "000" + number.ToString();
}
else if (number < 1000)
{
...
}
But this is a bit odd. Is there any built in function for my purpose?
Solution 1:[1]
Yes, there is:
string value = String.Format("{0:D5}", number);
Solution 2:[2]
According to the MS reference: http://msdn.microsoft.com/en-us/library/dd260048.aspx
You can pad an integer with leading zeros by using the "D" standard numeric format string together with a precision specifier. You can pad both integer and floating-point numbers with leading zeros by using a custom numeric format string.
So:
To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
Code:
string value = number.ToString("D5");
.NET fiddle: http://dotnetfiddle.net/0U9A6N
Solution 3:[3]
You should use the ToString() method with custom formating - see the docs. In particular the 0 specifier.
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
eg,
value = number.Tostring("00000");
Solution 4:[4]
string value = number.ToString("00000");
Solution 5:[5]
You can do it this way :
number.ToString("00000")
Solution 6:[6]
If you wish to return 5 digits numbers, you should use the PadLeft() function;
int Value = 101;
char pad = '0';
String sValue = Value.ToString();
sValue = sValue.s.PadLeft(5, char)
In this case, you don't have to test whether to add 1, 2 or 3 zeros, it'll automatically add the number of zeros needed to make it 5 digits number.
Solution 7:[7]
int input_number = Convert.ToInt32(txtinput.Text);
string number_value = input_number.ToString("00000");
I hope that it will solve your problem. It worked well for me in my previous project. Test this code in your development. It should be worked properly without doubt.
Solution 8:[8]
Same as @Jojo's answer, but using C# 6's interpolated strings:
var value = $"{number:00000}";
Solution 9:[9]
Apart from String.Format, You can also use String.PadLeft
value = number.ToString().PadLeft(5, '0');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jojo |
| Solution 2 | |
| Solution 3 | Kami |
| Solution 4 | Marc Gravell |
| Solution 5 | Damien |
| Solution 6 | Nadeem_MK |
| Solution 7 | Josh Crozier |
| Solution 8 | Bendik August Nesbø |
| Solution 9 |
