• Format函数(转)


    本文是一篇由博主翻译过来的译文,内容中英文对照。原文中给出的部分示例是C的代码,但是对于VB该部分的内容一样适用。实际上Format函数的内容属于.Net Freamework框架。

    "I see stuff like {0,-8:G2} passed in as a format string. What exactly does that do?" -- Very Confused String Formatter

    {0,-8:G2}这样的参数字符串传递给Format函数,它们到底起了怎样的作用了?

    The above format can be translated into this:

    以上形式的格式化字符串参数可以被抽象成以下形式:

    "{<argument index>[,<alignment>][:<formatString><zeros>]}"

    "{<索引参数>[,<长度参数>][:<格式化字符串><zeros>]}"

     

    argument index: This represent which argument goes into the string.

    索引参数:它代表出现在Format函数中字符串参数的索引

    01 String.Format("first = {0};second = {1}", "apple", "orange");

    02 String.Format("first = {1};second = {0}", "apple", "orange");

     gives the following strings:

    以上两行代码的输出结果如下:

     "first = apple;second = orange"

    "first = orange;second = apple"

     

     

    alignment (optional): This represent the minimal length of the string.

    长度参数(可选):标识输出字符串的最小长度

     Postive values, the string argument will be right justified and if the string is not long enough, the string will be padded with spaces on the left.

    Negative values, the string argument will be left justied and if the string is not long enough, the string will be padded with spaces on the right.

    If this value was not specified, we will default to the length of the string argument.

    该参数可以允许负值。当为正值时,输出字符串右对齐并且字符串长度未超过指定长度时,其左侧使用空格填充。当该值为负值时,输出字符串左对齐并且字符串长度不超过指定长度时,其右侧使用空格填充。如果省略了该参数,将使用默认长度。 

    String.Format("{0,-10}", "apple");      //"apple     "

    String.Format("{0,10}", "apple");       //"     apple"

     

    format string (optional): This represent the format code.

    格式化字符串)(可选):该参数标识字符串被格式化的样式

    Numeric format specifier is available as following table. (e.g. C, G...etc.)

    数字格式化标识符请参见下表

    Specifier
    Type Format Output Output
       
    (Passed (Passed
       
    Double 1.42) Int -12400)
    c Currency {0:c} $1.42 ($12,400)
    d Decimal (Whole number) {0:d} System. -12400
    FormatException
    e Scientific {0:e} 1.42E+00 -1.24E+04
    f Fixed point {0:f} 1.42 -12400
    g General {0:g} 1.42 -12400
    n Number with commas for thousands {0:n} 1.42 -12,400
    r Round trippable {0:r} 1.42 System.
    FormatException
    x Hexadecimal {0:x4} System. cf90
    FormatException

    Datetime format specifier is available as following table.

    日期时间格式化标识符请见下表所示

    Specifier
    Type Example (Passed System.DateTime.Now)
    d Short date 10/12/2002
    D Long date 10-Dec-02
    t Short time 10:11 PM
    T Long time 10:11:29 PM
    f Full date & time 2002-12-10 22:11
    F Full date & time (long) 2002-12-10 22:11
    g Default date & time 10/12/2002 10:11 PM
    G Default date & time (long) 10/12/2002 10:11:29 PM
    M Month day pattern 10-Dec
    r RFC1123 date string Tue, 10 Dec 2002 22:11:29 GMT
    s Sortable date string 2002-12-10T22:11:29
    u Universal sortable, local time 2002-12-10 22:13:50Z
    U Universal sortable, GMT 2002-12-11 3:13
    Y Year month pattern December, 2002

    Custom Datetime format specifier is available as following table.

    自定义日期时间格式标识符请见下表所示

    Specifier
    Type Example Example Output
    dd Day {0:dd} 10
    ddd Day name {0:ddd} Tue
    dddd Full day name {0:dddd} Tuesday
    f, ff, ... Second fractions {0:fff} 932
    gg, ... Era {0:gg} A.D.
    hh 2 digit hour {0:hh} 10
    HH 2 digit hour, 24hr format {0:HH} 22
    mm Minute 00-59 {0:mm} 38
    MM Month 01-12 {0:MM} 12
    MMM Month abbreviation {0:MMM} Dec
    MMMM Full month name {0:MMMM} December
    ss Seconds 00-59 {0:ss} 46
    tt AM or PM {0:tt} PM
    yy Year, 2 digits {0:yy} 2
    yyyy Year {0:yyyy} 2002
    zz Timezone offset, 2 digits {0:zz} -5
    zzz Full timezone offset {0:zzz} -05:00
    : Separator {0:hh:mm:ss} 10:43:20
    / Separator {0:dd/MM/yyyy} 10/12/2002

    Enumeration format specifier is available as following table.

    枚举型格式化标识符请见下表所示

    Specifier
    Type
    g Default (Flag names if available, otherwise decimal)
    f Flags always
    d Integer always
    x Eight digit hex.

    Custom Numeric format specifier is available as following table. (e.g. 0. #...etc.)

    自定义数字标识符请见下表所示

    Specifier
    Type Example Output (Passed Double 1500.42) Note
    0 Zero placeholder {0:00.0000} 1500.42 Pads with zeroes.
    # Digit placeholder {0:(#).##} (1500).42
    . Decimal point {0:0.0} 1500.4
    , Thousand separator {0:0,0} 1,500 Must be between two zeroes.

    Custom formatting is kind a hard to understand. The best way I know how to explain something is via code:

    自定义格式很难被理解,我所想到的最好的解释方法就是给出示例说明:

     

    int pos = 10;

    int neg = -10;

    int bigpos = 123456;

    int bigneg = -123456;

    int zero = 0;

    string strInt = "120ab";

     

    String.Format("{0:00000}", pos);      //"00010"

    String.Format("{0:00000}", neg);      //"-00010"

    String.Format("{0:00000}", bigpos);   //"123456"

    String.Format("{0:00000}", bigneg);   //"-123456"

    String.Format("{0:00000}", zero);     //"00000"

    String.Format("{0:00000}", strInt);   //"120ab"

    String.Format("{0:#####}", pos);      //"10"

    String.Format("{0:#####}", neg);      //"-10"

    String.Format("{0:#####}", bigpos);   //"123456"

    String.Format("{0:#####}", bigneg);   //"-123456"

    String.Format("{0:#####}", zero);     //""

    String.Format("{0:#####}", strInt);   //"120ab"

    While playing around with this, I made an interesting observation:

    一些有趣的示例 

    String.Format("{0:X00000}", pos);      //"A"

    String.Format("{0:X00000}", neg);      //"FFFFFFF6"

    String.Format("{0:X#####}", pos);      //"X10"

    String.Format("{0:X#####}", neg);      //"-X10"

     

    The "0" specifier works well with other numeric specifier, but the "#" doesn't. Umm... I think the "Custom Numeric Format String" probably deserve a whole post of it's own. Since this is only the "101" post, I'll move on to the next argument in the format string.

    "0"这个标识符和其他的数字标识符一起使用时工作十分正常,但是"#"就会出现些问题。

     

     

    zeros (optional): It actually has a different meaning depending on which numeric specifier you use.

     

    int neg = -10;

    int pos = 10;

    // C or c (Currency): It represent how many decimal place of zeros to show.

    String.Format("{0:C4}", pos);      //"$10.0000"

    String.Format("{0:C4}", neg);      //"($10.0000)"

     

    // D or d (Decimal): It represent leading zeros

    String.Format("{0:D4}", pos);      //"0010"

    String.Format("{0:D4}", neg);      //"-0010"

     

    // E or e (Exponential): It represent how many decimal places of zeros to show.

    String.Format("{0:E4}", pos);      //"1.0000E+001"

    String.Format("{0:E4}", neg);      //"-1.0000E+001"

     

    // F or f (Fixed-point): It represent how many decimal places of zeros to show.

    String.Format("{0:F4}", pos);      //"10.0000"

    String.Format("{0:F4}", neg);      //"-10.0000"

     

    // G or g (General): This does nothing

    String.Format("{0:G4}", pos);      //"10"

    String.Format("{0:G4}", neg);      //"-10"

     

    // N or n (Number): It represent how many decimal places of zeros to show.

    String.Format("{0:N4}", pos);      //"10.0000"

    String.Format("{0:N4}", neg);      //"-10.0000"

     

    // P or p (Percent): It represent how many decimal places of zeros to show.

    String.Format("{0:P4}", pos);      //"1,000.0000%"

    String.Format("{0:P4}", neg);      //"-1,000.0000%"

     

    // R or r (Round-Trip): This is invalid, FormatException is thrown.

    String.Format("{0:R4}", pos);      //FormatException thrown

    String.Format("{0:R4}", neg);      //FormatException thrown

     

    // X or x (Hex): It represent leading zeros

    String.Format("{0:X4}", pos);      //"000A"

    String.Format("{0:X4}", neg);      //"FFFFFFF6"

     

    // nothing: This is invalid, no exception is thrown.

    String.Format("{0:4}", pos));      //"4"

    String.Format("{0:4}", neg));      //"-4"

    In summary, there are four types of behaviour when using this <zeros> specifier:

    Leading Zeros: D, X

    Trailing Zeros: C, E, F, N, P

    Nothing: G

    Invalid: R, <empty>

     

    Now, that we've gone through the valid specifiers, you can actually use this in more than just String.Format(). For example, when using this with Byte.ToString():

     

    Byte b = 10;

    b.ToString("D4");      //"0010"

    b.ToString("X4");      //"000A"

     

    Wow... this was way longer than I expected. The BCL team is having blog day today, I need to get back to posting something for the BCLWeblog.

    <Editorial Comment>

    One of the lesson I learnt from an earlier post is that, readers are not interested in a post that doesn't give you more information than what MSDN provides. Instead, readers are more interested in seeing stuff that are not available on MSDN. So when I was doing research to post about this topic, I found that MSDN actually talks about exactly what the {0,-8:G2} format does. It is just not easy to find nor centrally located.

    For example, in the ToString MSDN Doc, the "Remarks" section covered some basic rules on what a "format string" is. In the String.Format MSDN Doc, the "Remarks" section actually have a pretty detail explaination of what the above format does. Furthermore, MSDN provides a format string overview as well as a the table that specifies all the values that are allowed.

    This puts me in an interesting position when writing about this topic. MSDN actually have lots of info that cover it. But since I have also heard more than one person being confused about this topic, I decided to post a summary of the documents and more examples. Do you think this is useful? Should I just stick to posting exclusively on non-MSDN topics?

  • 相关阅读:
    [机器学习案例1]基于KNN手写数字识别
    Android横竖屏切换View设置不同尺寸或等比例缩放的XML解决方案
    Qt之网络编程
    Redis系列-存储篇sorted set主要操作函数小结
    Code First Migrations更新数据库结构的具体步骤
    json文件解析
    go语言文件操作
    docker容器与主机之间的文件复制
    ubuntu16.04 安装docker
    Go语言string,int,int64 ,float之间类型转换方法
  • 原文地址:https://www.cnblogs.com/lsfv/p/1724872.html
Copyright © 2020-2023  润新知