简体   繁体   中英

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

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.

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.

My workaround is similar to how Qt implements QString::arg() . I just put a placeholder and then replaced it with the value of numericPrecision .

numericPrecision = "N2";
var summary = string.Format(
    "{0}: {1:_np_}, {2}: {3:_np_}, {4}: {5:_np_}".Replace("_np_", numericPrecision),
    title1, value1,
    title2, value2,
    title3, value3);

To format a string that is left justified for specified length.

int len = 20;
string fmt = string.Format( "{{0,-{0}}}", len );
string name = string.Format( fmt, "a persons name" );

or

name.PadRight( len );

The result should be a name that is padded on the right for a total length of 20 characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM