Using printf i could specify the precision value as an extra parameter using *. Does the same functionality exist in the C# String.Format?
edit: For example:
Console.WriteLine("{0:D*}",1,4); // Outputs 0001;
Using printf i could specify the precision value as an extra parameter using *. Does the same functionality exist in the C# String.Format?
edit: For example:
Console.WriteLine("{0:D*}",1,4); // Outputs 0001;
Yes this is possible. You just need to add the precision number after the format specifier. For example
Console.WriteLine("{0:D4}",1); // Outputs 0001;
What the precision modifier does is specific to the format type chosen though. In this case the D stands for Decimal output. Here is a link to the types of numeric formats and what the precision means for each of them.
No, String.Format does not support the star operator. You'd need to use either string concatenation
Console.WriteLine("{0:D" + myPrecision.ToString() + "}",1);
or nested String.Format
s
Console.WriteLine(String.Format("{{0:D{0}}}", 4), 1);
Formatting the format string should do the trick:
var number = 1;
var width = 4;
Console.WriteLine(String.Format("{{0:D{0}}}", width), number);
It will output 0001
.
Notice how {{
and }}
are used to escape {
and }
in a format string.