views:

47

answers:

3

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;
+1  A: 

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.

JaredPar
No, what I want is:Console.WriteLine("{0:D*}",1,4); // Outputs 0001;
Sprintstar
So then the answer to your question is no, @Sprintstar, c# implements similar syntax with the same functionality.
Matt Ellen
+2  A: 

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.Formats

Console.WriteLine(String.Format("{{0:D{0}}}", 4), 1);
Heinzi
+1  A: 

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.

Martin Liversage
+1 for explaining the syntax of escaping braces.
Heinzi