Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precision specifier as parameter like printf but in String.Format

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
like image 411
Sprintstar Avatar asked Aug 26 '10 16:08

Sprintstar


People also ask

Which format specifier is used to print a printf string?

We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character.

Is string format the same as printf?

String. format returns a new String, while System. out. printf just displays the newly formatted String to System.


2 Answers

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);
like image 180
Heinzi Avatar answered Sep 27 '22 23:09

Heinzi


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.

like image 22
Martin Liversage Avatar answered Sep 27 '22 23:09

Martin Liversage