【转载】format的用法。
2008-07-26 14:51 金色海洋(jyk) 阅读(1214) 评论(4) 编辑 收藏 举报以前没太注意这个用法,到网上找一个,copy过来,方便以后的查看。
"I see stuff like {0,-8:G2} passed in as a format string. What exactly does that do?" -- Very Confused String Formatter
The above format can be translated into this:
"{<argument index>[,<alignment>][:<formatString><zeros>]}"
argument index: This represent which argument goes into the string.
String.Format("first = {0};second = {1}", "apple", "orange");
String.Format("first = {1};second = {0}", "apple", "orange");
gives the following strings:
"first = apple;second = orange"
"first = orange;second = apple"
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 here. (e.g. C, G...etc.)
Datetime format specifier is available here.
Datetime format specifier is available here.
Enumeration format specifier is available here.
Custom Numeric format specifier is available here. (e.g. 0. #...etc.)
Custom formatting is kinda 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.
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?
</Editorial Comment>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!