C# ToString格式字符串整理(Format)(数字、日期和枚举的标准格式设置说明符)
日常开发中,格式字符串的情况非常多。经常也会忘记,经常去查有些麻烦,所以今天就花点时间做个整理。
格式字符串用的比较多的有数字、日期与枚举的格式化。
一、数字格式字符串
C或c | 本地货币格式 |
D或d | 十进制格式,把整数转换为以10为基数的书,如果给定一个精度说明符,就加上前导0 |
E或e | 科学计数法(指数)格式,精度说明符设置小数位数(默认为6),格式字符串的大小写(e或E)确定指数符号的大小写。 |
F或f | 固定点格式,精度说明符设置小数位数,可以为0 |
G或g | 普通格式,使用E或F格式取决于哪种格式较简单 |
N或n | 数字格式,用逗号表示千分符,例如32,767.44 |
P或p | 百分数格式 |
X或x | 十六进制格式,精度说明符用于加上前导0 |
先用例子说明几种格式字符串的方法:
double d = 123.456; Console.WriteLine("ToString:{0}", d.ToString("C")); Console.WriteLine("Format:{0}", string.Format("{0:C}",d)); Console.WriteLine("Console:{0:C}", d);
输出结果:
数字格式化程序例子:
Console.WriteLine("十六进制格式符X:{0}", (145).ToString("X"));//X只支持整型 double[] numbers = {1054.32179, -195489100.8377, 1.0437E21, -1.0573e-05}; string[] specifiers = { "C", "E", "F", "G", "N","P", "R","#,000.000", "0.###E-000", "000,000,000,000.00###" }; foreach (double number in numbers) { Console.WriteLine("Formatting of {0}:", number); foreach (string specifier in specifiers) { Console.WriteLine(" {0,5}: {1}", specifier, number.ToString(specifier)); } Console.WriteLine(); }
输出结果:
二、日期格式字符串
static void DateToString() { DateTime dateValue = DateTime.Now; // Create an array of standard format strings. string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o", "R", "s", "t", "T", "u", "U", "y"}; // Output date and time using each standard format string. foreach (string standardFmt in standardFmts) Console.WriteLine("{0}: {1}", standardFmt, dateValue.ToString(standardFmt)); Console.WriteLine(); // Create an array of some custom format strings. string[] customFmts = {"yyyyMMddHHmmss","h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f", "dd MMM HH:mm:ss", @"\Mon\t\h\: M", "HH:mm:ss.ffffzzz" }; // Output date and time using each custom format string. foreach (string customFmt in customFmts) Console.WriteLine("'{0}': {1}", customFmt, dateValue.ToString(customFmt)); }
输出结果:
三、枚举格式字符串
enum Colors { Red, Green, Blue, Yellow = 12 }; static void EnumToString() { Colors myColor = Colors.Yellow; Console.WriteLine("Colors.Red = {0}", Colors.Red.ToString("d")); Console.WriteLine("Colors.Green = {0}", Colors.Green.ToString("d")); Console.WriteLine("Colors.Blue = {0}", Colors.Blue.ToString("d")); Console.WriteLine("Colors.Yellow = {0}", Colors.Yellow.ToString("d")); Console.WriteLine("{0}myColor = Colors.Yellow{0}", Environment.NewLine); Console.WriteLine("myColor.ToString(\"g\") = {0}", myColor.ToString("g")); Console.WriteLine("myColor.ToString(\"G\") = {0}", myColor.ToString("G")); Console.WriteLine("myColor.ToString(\"x\") = {0}", myColor.ToString("x")); Console.WriteLine("myColor.ToString(\"X\") = {0}", myColor.ToString("X")); Console.WriteLine("myColor.ToString(\"d\") = {0}", myColor.ToString("d")); Console.WriteLine("myColor.ToString(\"D\") = {0}", myColor.ToString("D")); Console.WriteLine("myColor.ToString(\"f\") = {0}", myColor.ToString("f")); Console.WriteLine("myColor.ToString(\"F\") = {0}", myColor.ToString("F")); }
输出结果: