C# 字符串格式化整理
使用方式1: xxx.ToString(xxxx)
使用方式2:string.Format(xxxx,xxx)
1、占位符格式化
零占位符:固定位数,不足补充0
数字占位符:最小化数字展示,“##”格式字符串使得值被舍入到小数点前最近的数字,其中零总被舍去。
空格占位符
string.Format("{0,-50}", theObj);//格式化成50个字符,原字符左对齐,不足则补空格
string.Format("{0,50}", theObj);//格式化成50个字符,原字符右对齐,不足则补空格
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
自定义数值格式:
Specifier
|
Type
|
Example
|
Output (Passed Double 1500.42)
|
Note
|
0
|
Zero placeholder
|
{0:00.0000}
|
1500.4200
|
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.
|
,.
|
Number scaling
|
{0:0,.}
|
2
|
Comma adjacent to Period scales by 1000.
|
%
|
Percent
|
{0:0%}
|
150042%
|
Multiplies by 100, adds % sign.
|
e
|
Exponent placeholder
|
{0:00e+0}
|
15e+2
|
Many exponent formats available.
|
;
|
Group separator see below
|
|
|
|
百分比格式化:
Console.WriteLine((0.1234).ToString("P0"));//12%
Console.WriteLine((0.1234).ToString("P"));//12.34%
Console.WriteLine(string.Format("{0:P2}",0.12345));//12.35%
2. 常用数字类型格式化:
字符串格式符号
|
说明
|
代码示例
|
输出
|
C
|
货币
|
2.5.ToString(“C”)
|
¥2.50
|
D
|
十进制
|
25.ToString(“D5”)
|
00025
|
E
|
科学计数法
|
25000.ToString(“E”)
|
2.500000E+005
|
F
|
固定小数点位数
|
25.ToString(“F2”)
|
25.00
|
G
|
常规
|
2.5.ToString(“G”)
|
2.5
|
N
|
数值
|
2500000.ToString(“N”)
|
2,500,000.00
|
X
|
十六进制
|
255.ToString(“X”)
|
F
F
|
基本数字格式说明符:
Specifier
|
Type
|
Format
|
Output (Passed Double 1.42)
|
Output (Passed Int -12400)
|
c
|
Currency
|
{0:c}
|
$1.42
|
-$12,400
|
d
|
Decimal (Whole number)
|
{0:d}
|
System.FormatException
|
-12400
|
e
|
Scientific
|
{0:e}
|
1.420000e+000
|
-1.240000e+004
|
f
|
Fixed point
|
{0:f}
|
1.42
|
-12400.00
|
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.FormatException
|
cf90
|
3.时间类型格式化:
稍后见另一篇文章