Reputation: 12455
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 ?
Upvotes: 1
Views: 2421
Reputation: 849
The .ToString() function have multiple formats you can choose from (on any numeric type).
Format Digits
Will add '0' prefix based on D#.
var number = 8;
var formattedNumber = number.ToString("D2");
Console.WriteLine(formattedNumber); // Output: 08
Seperator
var number = 123456789;
var formattedNumber = number.ToString("#,###");
Console.WriteLine(formattedNumber); // Output: 123,456,789
Check the official MS Docs for more information
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
Upvotes: 0
Reputation: 28586
?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"
Upvotes: 17
Reputation: 797
I would use the .ToString() parameter but here is another option:
int i = 8;
i.ToString.PadLeft(2, (char)"0")
Upvotes: 2