【转载】format的用法。

以前没太注意这个用法,到网上找一个,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.

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>

 

 

http://www.diybl.com/course/3_program/c++/cppjs/20091124/183329.html

 

 

时间: 2024-09-20 00:25:44

【转载】format的用法。的相关文章

format的用法

现在用电脑的人都知道软盘,但你知道新买来的软盘是不能直接使用的吗?(这概念有点过时,因为现在有很多厂家生产的软盘都先帮你格式化过,不过这命令还是不能不学,因为太有用)新买的软盘你既不能用copy命令向软盘上复制文件,也不能用dir命令查看软盘上的内容,甚至从键盘上输入A:都会引起错误.这是为什么呢? 因为软盘在使用前需要先格式化,在软盘上作出许多位置标记,然后才能向上面填写数据和文字,这就好象在一张白纸上画格子,然后再在这些格子中写字一样.这个在软盘上打格子的过程,就叫格式化.给软盘格式化,要使

java format的用法

问题描述 importjava.util.Date;publicclassdate{/***@paramargs*/publicstaticvoidmain(String[]args){Datedate=newDate();Stringyear=String.format("%tY",date);Stringmonth=String.format("%tB",date);Stringday=String.format("%ta",date);Sy

asp.net format函数用法(c#版)

Format函数 返回 返回 Variant (String),其中含有一个表达式,它是根据格式表达式中的指令来格式化的. 语法 Format(expression[, format[, firstdayofweek[, firstweekofyear]]]) C# Format函数的语法具有下面几个部分: 部分 说明 expression 必要参数.任何有效的表达式. format 可选参数.有效的命名表达式或用户自定义格式表达式. firstdayofweek 可选参数.常数,表示一星期的第

MySQL的format函数用法详解

FORMAT()函数是用来在以下格式来格式化数X:###,###,#####截断至D位小数.下面的例子演示了如何使用和输出的FORMAT()函数:  代码如下 复制代码 mysql>SELECT FORMAT(423423234.65434453,2); +---------------------------------------------------------+ | FORMAT(423423234.65434453,2)                            | +-

Python中用format函数格式化字符串的用法_python

自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足.那么,他跟之前的%型格式化字符串相比,有什么优越的存在呢?让我们来揭开它羞答答的面纱.语法 它通过{}和:来代替%. "映射"示例 通过位置 In [1]: '{0},{1}'.format('kzc',18) Out[1]: 'kzc,18' In [2]: '{},{}'.format('kzc',18) Out[2]: 'kzc,18' In [3]: '{1},{0},{1}'.for

sql format()函数的用法及简单实例_Mysql

FORMAT() 函数用于对字段的显示进行格式化. SQL FORMAT() 语法 SELECT FORMAT(column_name,format) FROM table_name; 参数 描述 column_name 必需.要格式化的字段. format 必需.规定格式.  演示数据库 在本教程中,我们将使用众所周知的 Northwind 样本数据库. 下面是选自 "Products" 表的数据: ProductID ProductName SupplierID CategoryI

ASP中FormatDateTime函数用法详解

FormatDateTime 函数 返回表达式,此表达式已被格式化为日期或时间. FormatDateTime(Date[, NamedFormat]) 参数 参数 描述 date Required. Any valid date expression (like Date() or Now()) 必选项.要被格式化的日期表达式.(如Date()或Now()) format Optional. A Format value that specifies the date/time format

浅析AngularJS Filter用法_AngularJS

系统的学习了一下angularjs,发现angularjs的有些思想根php的模块smarty很像,例如数据绑定,filter.如果对smarty比较熟悉的话,学习angularjs会比较容易一点,这篇文章给大家介绍angularjs filter用法详解,感兴趣的朋友一起学习吧 Filter简介 Filter是用来格式化数据用的. Filter的基本原型( '|' 类似于Linux中的管道模式): 复制代码 代码如下: {{ expression | filter }} Filter可以被链式

ASP.NET MVC功能详解 变身数据展示达人

作为Web开发者,我们经常面对的任务就是将数据通过表格展现给用户.最简单的情景是比如仅将顾客的订单显示出来.然而,更多的数据表格将提供比如排序,分页等更多的丰富的功能. 在ASP.NET的web表单中,GridView控件提供了一种快速简便的方法显示网格中的记录集,并提供像排序.分页.编辑及删除的功能,所有的这些只需写少量的代码就可以实现.在页面加载时,GridView自动HTML中的table标记,让你不需要写任何标签,以及不用去考虑如何显示和将数据绑定到GridView控件.在ASP.NET