1

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 ?

4 Answers 4

17
?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"
4
  • It took me a while to recall that ? is a BASIC short cut to print a value to the console. Commented Dec 18, 2009 at 22:06
  • '?' is the symbol used in the Immediate Window of Visual Studio for obtain variable values :)
    – serhio
    Commented Dec 18, 2009 at 22:31
  • 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 :) Commented Dec 30, 2009 at 16:18
  • 1
    @Mark: Yes. I am €uropean! With meters, Euros, Kilograms and Celsius degrees :)
    – serhio
    Commented Dec 30, 2009 at 16:29
4
i.ToString("D2")
0
2

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

int i = 8;
i.ToString.PadLeft(2, (char)"0")
-1

Standard Numeric Format Strings

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 Numeric Format Strings

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.

See Also

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.