tags:

views:

196

answers:

5

I have:

int i=8;
i.ToString();

if i do this i get "8" i want "08"

is possible setting an option in tostring parameter ?

+14  A: 
?8.ToString("00")
"08"
?8.ToString("000")
"008"
?128.ToString("000")
"128"
?128.ToString("000.00")
"128,00"
?128.ToString("0000.##")
"0128"

Also you can use the string.Format() methods (like String.Format("{0,10:G}: {0,10:X}", value)) or display your number in Standard or Custom Numeric Format Strings.

Other useful examples:

?5/3
1.6666666666666667
?String.Format("{0:0.00}", 5/3)
"1,67"
?System.Math.Round(5/3, 2)
1.67
?(5.0 / 3).ToString("0.00")
"1,67"
?(5 / 3).ToString("0.00")
"1,00"
?(5.0 / 3).ToString("E") //Exponential
"1,666667E+000"
?(5.0 / 3).ToString("F") //Fixed-point
"1,67"
?(5.0 / 3).ToString("N") //Number
"1,67"
?(5.0 / 3).ToString("C") //Currency
"1,67 €"
?(5.0 / 3).ToString("G") //General
"1,66666666666667"
?(5.0 / 3).ToString("R") //Round-trip
"1,6666666666666667"
?(5.0 / 3).ToString("this is it .")
"this is it 2"
?(5.0 / 3).ToString("this is it .0")
"this is it 1,7"
?(5.0 / 3).ToString("this is it .0##")
"this is it 1,667"
?(5.0 / 3).ToString("this is it #####")
"this is it 2"
?(5.0 / 3).ToString("this is it .###")
"this is it 1,667"
serhio
more info here: http://msdn.microsoft.com/en-us/library/8wch342y.aspx
Bert Lamb
It took me a while to recall that `?` is a BASIC short cut to print a value to the console.
Steve Guidi
'?' is the symbol used in the Immediate Window of Visual Studio for obtain variable values :)
serhio
It may be obvious but serhio has a set up for "," to be the decimal and Euro for currency so 1,667 = 1.667 for others...for those not quite awake yet :)
Mark Schultheiss
@Mark: Yes. I am *€uropean*! With meters, Euros, Kilograms and Celsius degrees :)
serhio
A: 

I can't understand what do you mean by that. Why don't you add 0 to a string manually?

vasin
That would not be exactly a good approach, for instance, it is a bit too rigid. Please look at Serhio's answer which, is more flexible and safest approach, and that is what the OP was looking for! :)
tommieb75
+1 since the answer is perfectly valid - the original question does not make clear what should happen for example to i=18. Who says Luca does not want "018" as a result?
Doc Brown
+4  A: 
i.ToString("D2")
James Keesey
+1, this is the best solution to me.
Jay Zeng
+1  A: 

I would use the .ToString() parameter but here is another option:

int i = 8;
i.ToString.PadLeft(2, (char)"0")
ShaunLMason
+1  A: 

I've found the following link useful when dealing with string formatting in C#:

http://blog.stevex.net/string-formatting-in-csharp/

chlb