普通格式化:
Code
int a = 12345;
Console.WriteLine(12345.ToString());
//格式化为数字,取决于当前线程选择的CurrentCulture
Console.WriteLine(12345.ToString("n"));
double val = Math.PI;
Console.WriteLine(val.ToString());
//格式化为科学计数法
Console.WriteLine(val.ToString("E"));
//格式化保留3位小数
Console.WriteLine(val.ToString("F3"));
int val1 = 65535;
//格式化为16进制
Console.WriteLine(val1.ToString("x"));
Console.WriteLine(val1.ToString("X"));
//格式化为百分数
Single val2 = 0.653F;
Console.WriteLine(val2.ToString("p"));
Console.WriteLine(val2.ToString("p1"));
double val3 = 12345.89;
//格式化为货币
Console.WriteLine(val3.ToString("C"));
int a = 12345;
Console.WriteLine(12345.ToString());
//格式化为数字,取决于当前线程选择的CurrentCulture
Console.WriteLine(12345.ToString("n"));
double val = Math.PI;
Console.WriteLine(val.ToString());
//格式化为科学计数法
Console.WriteLine(val.ToString("E"));
//格式化保留3位小数
Console.WriteLine(val.ToString("F3"));
int val1 = 65535;
//格式化为16进制
Console.WriteLine(val1.ToString("x"));
Console.WriteLine(val1.ToString("X"));
//格式化为百分数
Single val2 = 0.653F;
Console.WriteLine(val2.ToString("p"));
Console.WriteLine(val2.ToString("p1"));
double val3 = 12345.89;
//格式化为货币
Console.WriteLine(val3.ToString("C"));
结果:
12345
12,345.00
3.14159265358979
3.141593E+000
3.142
ffff
FFFF
65.30%
65.3%
¥12,345.89
格式化枚举:
Code
enum Music
{
Rock = 1,
Blues = 2,
Jazz = 3,
Classical = 4
}
//格式化枚举
Music myMusic = Music.Blues;
Console.WriteLine(myMusic.ToString("G"));
Console.WriteLine(myMusic.ToString("d"));
DayOfWeek day = DayOfWeek.Tuesday;
Console.WriteLine(string.Format("My favorite day is {0:d}",day));
enum Music
{
Rock = 1,
Blues = 2,
Jazz = 3,
Classical = 4
}
//格式化枚举
Music myMusic = Music.Blues;
Console.WriteLine(myMusic.ToString("G"));
Console.WriteLine(myMusic.ToString("d"));
DayOfWeek day = DayOfWeek.Tuesday;
Console.WriteLine(string.Format("My favorite day is {0:d}",day));
结果:
Blues
2
My favorite day is 2
My favorite day is Tuesday
补充:格式说明符和用法示例