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 ?
?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"
?
is a BASIC short cut to print a value to the console.
Commented
Dec 18, 2009 at 22:06
I would use the .ToString() parameter but here is another option:
int i = 8;
i.ToString.PadLeft(2, (char)"0")
Decimal Format (D2):
int number = 8;
string formattedNumber = number.ToString("D2");
Console.WriteLine(formattedNumber); // Output: 08
This example formats an integer value number
with the "D2"
format specifier. It ensures that the number is represented with at least two digits, adding leading zeros if necessary.
Custom Thousand Separator Format (#,###):
int population = 123456789;
string formattedPopulation = population.ToString("#,###");
Console.WriteLine(formattedPopulation); // Output: 123,456,789
This example formats an integer value population
to include thousand separators using the custom format string "#,###"
. It adds commas to denote thousands and groups digits accordingly for better readability.