string类(三、string.format格式字符串)

参考连接:
http://www.cnblogs.com/luluping/archive/2009/04/30/1446665.html
http://blog.csdn.net/samsone/article/details/7556781

0.一般:
string.Format(“{0}–{1}–{2}”,a,b,c)占位符
1. 格式化货币(跟系统的环境有关,中文系统默认格式化人民币,英文系统格式化美元)
string.Format(“{0:C}”,0.2) Result:¥0.20 (英文操作系统结果:$0.20)

默认格式化小数点后面保留两位小数,如果需要保留一位或者更多,可以指定位数
string.Format(“{0:C1}”,23.15) Result:¥23.2 (截取会自动四舍五入)
格式化多个Object: string.Format(“市场价:{0:C},优惠价{1:C}”,23.15,19.82)
2. 格式化十进制的数字(格式化成固定的位数不足时前面补0足时无操作,位数不能少于未格式化前,只支持整型)
string.Format(“{0:D3}”,23) 结果为:023
string.Format(“{0:D2}”,1223) 结果为:1223,(精度说明符指示结果字符串中所需的最少数字个数。)

格式化小数(小数点后四舍五入保留n位)
string.Format(“0:f2”,1.228) 结果为:1.23
3. 用逗号隔开的数字,并指定小数点后的位数 (默认为小数点后面两位,否则保留n位)
string.Format(“{0:N}”, 14200) 结果为:14,200.00
string.Format(“{0:N3}”, 14200.2458) 结果为:14,200.246 (自动四舍五入)
4. 格式化百分比 (默认保留百分的两位小数;否则保留n位)
string.Format(“{0:P}”, 0.24583) 结果为:24.58%
string.Format(“{0:P1}”, 0.24583) 结果为:24.6% (自动四舍五入)
5. 零占位符和数字占位符
string.Format(“{0:0000.00}”, 12394.039) 结果为:12394.04
string.Format(“{0:0000.00}”, 194.039) 结果为:0194.04
string.Format(“{0:###.##}”, 12394.039) 结果为:12394.04
string.Format(“{0:####.#}”, 194.039) 结果为:194

下面的这段说明比较难理解,多测试一下实际的应用就可以明白了。
零占位符:
如果格式化的值在格式字符串中出现“0”的位置有一个数字,则此数字被复制到结果字符串中。小数点前最左边的“0”的位置和小数点后最右边的“0”的位置确定总在结果字符串中出现的数字范围。
“00”说明符使得值被舍入到小数点前最近的数字,其中零位总被舍去。

数字占位符:
如果格式化的值在格式字符串中出现“#”的位置有一个数字,则此数字被复制到结果字符串中。否则,结果字符串中的此位置不存储任何值。
请注意,如果“0”不是有效数字,此说明符永不显示“0”字符,即使“0”是字符串中唯一的数字。如果“0”是所显示的数字中的有效数字,则显示“0”字符。
“##”格式字符串使得值被舍入到小数点前最近的数字,其中零总被舍去。

PS:空格占位符
string.Format(“{0,-50}”, theObj);//格式化成50个字符,原字符左对齐,不足则补空格
string.Format(“{0,50}”, theObj);//格式化成50个字符,原字符右对齐,不足则补空格
6. 日期格式化
string.Format(“{0:d}”,System.DateTime.Now) 结果为:2009/3/20 (月份位置不是03)
string.Format(“{0:D}”,System.DateTime.Now) 结果为:2009年3月20日
string.Format(“{0:f}”,System.DateTime.Now) 结果为:2009年3月20日 15:37
string.Format(“{0:F}”,System.DateTime.Now) 结果为:2009年3月20日 15:37:52
string.Format(“{0:g}”,System.DateTime.Now) 结果为:2009/3/20 15:38
string.Format(“{0:G}”,System.DateTime.Now) 结果为:2009-3-20 15:39:27
string.Format(“{0:m}”,System.DateTime.Now) 结果为:3月20日
string.Format(“{0:t}”,System.DateTime.Now) 结果为:15:41
string.Format(“{0:T}”,System.DateTime.Now) 结果为:15:41:50
图文:

Numbers:
这里写图片描述

Custom number formatting:
这里写图片描述

这里写图片描述

Dates:
这里写图片描述

Custom date formatting:
这里写图片描述

原文地址:https://www.cnblogs.com/caymanlu/p/6361678.html