现在的位置: 首页 > 综合 > 正文

DataFormatString–格式化字符串

2013年09月19日 ⁄ 综合 ⁄ 共 2527字 ⁄ 字号 评论关闭

 

程序:

public partial class FormatStrings : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
  double x = 2005.5;
  int y = 128;
  double z = 0.25;

  Response.Write(x.ToString() + " 以C2格式化之后 " + String.Format("{0:C2}", x) + "<BR>");
  Response.Write(y.ToString() + " 以D格式化之后 " + String.Format("{0:D}", y) + "<BR>");
  Response.Write(x.ToString() + " 以E2格式化之后 " + String.Format("{0:E2}", x) + "<BR>");
  Response.Write(x.ToString() + " 以F4格式化之后 " + String.Format("{0:F4}", x) + "<BR>");
  Response.Write(x.ToString() + " 以G格式化之后 " + String.Format("{0:G}", x) + "<BR>");
  Response.Write(x.ToString() + " 以N3格式化之后 " + String.Format("{0:N3}", x) + "<BR>");
  Response.Write(z.ToString() + " 以P格式化之后 " + String.Format("{0:P}", z) + "<BR>");
  Response.Write(y.ToString() + " 以X格式化之后 " + String.Format("{0:X}", y) + "<BR>");
  Response.Write(x.ToString() + " 以00####.00格式化之后 " + String.Format("{0:00####.00}", x) + "<BR>");
    }

效果:

2005.5 以C2格式化之后 ¥2,005.50
128 以D格式化之后 128
2005.5 以E2格式化之后 2.01E+003
2005.5 以F4格式化之后 2005.5000
2005.5 以G格式化之后 2005.5
2005.5 以N3格式化之后 2,005.500
0.25 以P格式化之后 25.00%
128 以X格式化之后 80
2005.5 以00####.00格式化之后 002005.50

更多:

DataFormatString="{0:格式字符串}"

在DataFormatString 中的 {0} 表示数据本身,而在冒号后面的格式字符串代表所们希望数据显示的格式;

数字、货币格式:
在指定的格式符号后可以指定小数所要显示的位数。例如原来的数据为「1.56」,若格式设定为 {0:N1},则输出为「1.5」。其常用的数值格式如下表所示:

格式字符串 输入 结果
"{0:C}" 12345.6789 $12,345.68
"{0:C}" -12345.6789 ($12,345.68)
"{0:D}" 12345 12345
"{0:D8}" 12345 00012345
"{0:E}" 12345.6789 1234568E+004
"{0:E10}" 12345.6789 1.2345678900E+004
"{0:F}" 12345.6789 12345.68
"{0:F0}" 12345.6789 12346
"{0:G}" 12345.6789 12345.6789
"{0:G7}" 123456789 1.234568E8
"{0:N}" 12345.6789 12,345.68
"{0:N4}" 123456789 123,456,789.0000
"Total: {0:C}" 12345.6789 Total: $12345.68

常用的日期时间格式:

格式 说明 输出格式
d 精简日期格式 MM/dd/yyyy
D 详细日期格式 dddd, MMMM dd, yyyy
f 完整格式 (long date + short time) dddd, MMMM dd, yyyy HH:mm
F
完整日期时间格式
(long date + long time)
dddd, MMMM dd, yyyy HH:mm:ss
g 一般格式 (short date + short time) MM/dd/yyyy HH:mm
G 一般格式 (short date + long time) MM/dd/yyyy HH:mm:ss
m,M 月日格式 MMMM dd
s 适中日期时间格式 yyyy-MM-dd HH:mm:ss
t 精简时间格式 HH:mm
T 详细时间格式 HH:mm:ss  

用DataFormatString格式化GridView

在GridView里面显示数据,要显示的数据有好多位小数,就想让它只显示两位小数,在delphi里,直接用DisplayFormat就行了,在.net中,查了半天msdn,发现使用DataFormatString是可以实现这个功能的,但是怎么设置就不起作用,最后发现,由于2.0出于安全性的考虑,还要同时设置HtmlEncode = false,才能够使DataFormatString生效.
留个记号,下次用的时候,就不用浪费N多时间了.
还有还有,DataFormatString = "{0:F}",是默认格式,显示两位小数,如果需要显示的小数位数为其他值,DataFormatString = "{0:Fn}"即可.

 

DataFormatString用于获取或设置指定列中各项的显示格式的字符串。

    形式为{A:Bxx}。例如,格式化字符串{0:F2}将显示带两位小数的定点数。

       其中A值只能设置为0,因为每个单元格中只有一个值。
       冒号后的字符(常规示例中为B)指定值的显示格式
       C 以货币格式显示数值。
       D 以十进制格式显示数值。
       E 以科学记数法(指数)格式显示数值。
       F 以固定格式显示数值。
       G 以常规格式显示数值。
       N 以数字格式显示数值。
       X 以十六进制格式显示数值。

抱歉!评论已关闭.